First, Generics Overview:
1. Source: 1.5jdk new features appear; to solve security problems, it is a security mechanism;
// The following code, compile no error, operating error, plus the given set of generic type defined;
2. Benefits: reduce runtime issues, reflected at compile time; to avoid the trouble of a cast;
3. Keyword: < data type >
public class Test { public static void main(String[] args) { ArrayList arrayList = new ArrayList(); arrayList.add("1"); arrayList.add(1); for (Iterator iterator = arrayList.iterator(); iterator.hasNext(); ) { String next = (String) iterator.next(); } } }
Second, generic usage:
1) generic class: class class name <T>
class Base<T> { private T t; public T getT() { return t; } public void setT(T t) { this.t = t; } } public class Test { public static void main(String[] args) { Base<String> s = new Base<String>(); s.setT("s"); System.out.println(s.getT()); } }
2) generic method: Modifier <T> return type method name (T T) {} ;
class Demo { public <T> void show(T t){ System.out.println(t); } } public class Test { public static void main(String[] args) { Demo demo = new Demo(); demo.show("string"); demo.show(123); } }
3) static generic method:
// common ways to access generic class definition, but not static methods, static methods can only define your own;
// format; modifier static <T> return type method name (T T) {} ; <T> must not be placed on top of static;
4) generic interface: interface interface name <T>
interface Inter<T>{ void show(T t); } class InterImpl implements Inter<String> { @Override public void show(String s) { System.out.println(s); } } public class Test { public static void main(String[] args) { InterImpl inter = new InterImpl(); inter.show("s"); } }
Third, the generic defined:
1, wildcard:? ; It can be understood as a placeholder;
2, Usage:
1 ) ? E the extends : upper; may receive E type or E subtypes;
2 ) ? Super E : The lower limit; may receive E type or E supertype;
Third, examples:
import java.util. *;
class Person{
private String name;
public Person(String name) {this.name = name;}
public String getName() { return name;}
}
class Student extends Person{
public Student(String name) {super(name); }
}
public class Test {
public static void main(String[] args) {
ArrayList<Person> al1=new ArrayList<Person>();
al1.add(new Person("张三"));
al1.add(new Person("李四"));
al1.add(new Person("王五"));
ArrayList<Student> al2=new ArrayList<Student>();
al2.add(new Student("刘一"));
al2.add (new Student ( "Liu II"));
al2.add(new Student("刘三"));
printAll(al1);
printAll(al2);
}
public static void printAll(ArrayList<? extends Person> al){
Iterator<? extends Person> it=al.iterator();
while (it.hasNext()){
System.out.println(it.next().getName());
}}}