Home >Java >javaTutorial >Code sharing for generic qualification in Java
This article mainly introduces the relevant content of Java programming generic limitation, which has certain reference value. Friends who need it can learn about it.
Generics generally appear in collections and also in iterators!
Generics are used to improve code security. Generics ensure the uniqueness of data types.
Among our commonly used containers, the simpler they are, the better they can be handled!
Generic qualification:
? Is a wildcard character that refers to any type
The upper limit of generics:
2d4902c92e1e7bfd574f59708c57776a accepts E or a subtype of E.
The lower limit of generics:
0d74ac1b2f8f9ab0eb66f930789a9645 receives E or the parent class of E.
The limited upper limit of generics (define the parent class to fill in the subclass type!)
Let’s take a look at the specific code example
package newFeatures8; import java.util.*; /* ? 通配符。也可以理解为占位符。 泛型的限定; ? extends E: 可以接收E类型或者E的子类型。上限。 ? super E: 可以接收E类型或者E的父类型。下限 */ class GenericDemo6 { public static void main(String[] args) { /* * ArrayList<String> al = new ArrayList<String>(); * * al.add("abc1"); al.add("abc2"); al.add("abc3"); * * ArrayList<Integer> al1 = new ArrayList<Integer>(); al1.add(4); * al1.add(7); al1.add(1); * * printColl(al); printColl(al1); */ //ArrayList<Person> al = new ArrayList<Student>();error //为了解决等号两边泛型不一致的情况,jdk1.7以后可以这么写 ArrayList<Person> al = new ArrayList<>();//右边的泛型自动反射进来 al.add(new Person("abc1")); al.add(new Person("abc2")); al.add(new Person("abc3")); // printColl(al); ArrayList<Student> al1 = new ArrayList<Student>(); al1.add(new Student("abc--1")); al1.add(new Student("abc--2")); al1.add(new Student("abc--3")); printColl(al1); } public static void printColl(Collection<? extends Person> al) { Iterator<? extends Person> it = al.iterator(); while (it.hasNext()) { System.out.println(it.next().getName()); } } /*public static void printColl(ArrayList<?> al) { Iterator<?> it = al.iterator(); while (it.hasNext()) { System.out.println(it.next().toString()); } }*/ } class Person { private String name; Person(String name) { this.name = name; } public String getName() { return name; } } class Student extends Person { Student(String name) { super(name); } } /* class Student implements Comparable<Person> { public int compareTo(Person s){ this.getName() } } */ /* class Comp implements Comparator<Person>{ //<? super E> public int compare(Person s1,Person s2) { //Person s1 = new Student("abc1"); return s1.getName().compareTo(s2.getName()); } } TreeSet<Student> ts = new TreeSet<Student>(new Comp());//TreeSet(Comparator<? super E> comparator) ts.add(new Student("abc1")); ts.add(new Student("abc2")); ts.add(new Student("abc3")); */
Summary
The above is the detailed content of Code sharing for generic qualification in Java. For more information, please follow other related articles on the PHP Chinese website!