The so-called generics: It allows specifying type parameters when defining classes and interfaces. This type parameter will be determined when declaring variables and creating objects (that is, passing in actual type parameters, which can also be called type arguments)
Generic class or interface
"Diamond" syntax
//定义 public interface List<E> extends Collection<E> public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable //使用 List<String> list = new ArrayList(); //Java7以后可以省略后面尖括号的类型参数 List<String> list = new ArrayList<>();
Deriving a subclass from a generic class
//方式1 public class App extends GenericType<String> //方式2 public class App<T> extends GenericType<T> //方式3 public class App extends GenericType
Pseudo-generic
There is no real generic class. Generic classes are transparent to the Java virtual machine. The JVM does not know the existence of generic classes. In other words, the JVM processes generic classes no differently from ordinary classes. Therefore, type parameters are not allowed in static methods, static initialization blocks, and static variables.
- The following methods are all wrong
private static T data; static{ T f; } public static void func(){ T name = 1; }
The following example can verify from the side that there is no generic class
public static void main(String[] args){ List<String> a1 = new ArrayList<>(); List<Integer> a2 = new ArrayList<>(); System.out.println(a1.getClass() == a2.getClass()); System.out.println(a1.getClass()); System.out.println(a2.getClass()); }
Output
true class java.util.ArrayList class java.util.ArrayList
Type wildcard
First of all, it must be clear that if Foo is the parent class of Bar, but List
The following methods will cause compilation errors:
List<?> list = new ArrayList<>(); list.add(new Object());
A few ideas:
1. List
2. Arrays are different from generics: assuming Foo is a subtype (subclass or subinterface) of Bar, then Foo[] is still a subtype of Bar[]; but G
3. In order to represent the parent class of various generic Lists, we need to use type wildcards. The type wildcard is a question mark (?). Pass a question mark as a type argument to the List collection, writing: List< ?> (meaning List of unknown type elements). This question mark (?) is called a wildcard character, and its element type can match any type.
The upper limit of wildcards
List extends SuperType> represents the parent class of all SuperType generic Lists or itself. Generics with wildcard upper limits cannot have set methods, only get methods.
Setting the upper limit of wildcards can solve the following problems: Dog is an Animal subclass, and there is a getSize method to get the number of incoming Lists. The code is as follows
abstract class Animal { public abstract void run(); } class Dog extends Animal { public void run() { System.out.println("Dog run"); } } public class App { public static void getSize(List<Animal> list) { System.out.println(list.size()); } public static void main(String[] args) { List<Dog> list = new ArrayList<>(); getSize(list); // 这里编译报错 } }
The reason for the programming error here is that List< Animal> is not the parent class of List
Lower limit of wildcard character
List super SubType> represents the lower limit of SubType generic List. Generics with wildcard upper limits cannot have get methods, only set methods.
Generic method
If you define a class or interface without using type parameters, but you want to define the type parameters yourself when defining a method, this is also possible. JDK1.5 also provides generic type method support. The method signature of a generic method has more type parameter declarations than the method signature of an ordinary method. The type parameter declarations are enclosed in angle brackets. Multiple type parameters are separated by commas (,). All type parameter declarations are placed Between the method modifier and the method return value type. The syntax format is as follows:
修饰符 返回值类型 方法名(类形列表){ //方法体 }
Generic methods allow type parameters to be used to express type dependencies between one or more parameters of the method, or method Type dependencies between return values and parameters. If there is no such type dependency, generic methods should not be used. The copy method of Collections uses a generic method:
public static <T> void copy(List<? super T> dest, List<? extends T> src){ ...}
This method requires that the src type must be a subclass of the dest type or itself.
Erase and Convert
In strict generic code, classes with generic declarations should always have type parameters. However, in order to be consistent with old Java code, it is also allowed to use classes with generic declarations without specifying type parameters. If no type parameter is specified for this generic class, the type parameter is called a raw type and defaults to the first upper limit type specified when the parameter is declared.
When an object with generic information is assigned to another variable without generic information, all type information between angle brackets is thrown away. For example, if a List
Example
class Apple<T extends Number> { T size; public Apple() { } public Apple(T size) { this.size = size; } public void setSize(T size) { this.size = size; } public T getSize() { return this.size; } } public class ErasureTest { public static void main(String[] args) { Apple<Integer> a = new Apple<>(6); // ① // a的getSize方法返回Integer对象 Integer as = a.getSize(); // 把a对象赋给Apple变量,丢失尖括号里的类型信息 Apple b = a; // ② // b只知道size的类型是Number Number size1 = b.getSize(); // 下面代码引起编译错误 Integer size2 = b.getSize(); // ③ } }
For more detailed explanations of generics in Java and related articles, please pay attention to the PHP Chinese website!