Home  >  Article  >  Java  >  Detailed explanation of generics in Java

Detailed explanation of generics in Java

高洛峰
高洛峰Original
2017-01-18 10:54:111316browse

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 List4ee996100bf04ab273e687539c860625 is not the parent class of Listad40e550a33cb99ea30eede96e03e60e. In order to represent various generic parent classes, Java uses "?" to represent generic general Matching. That is, List6b3d0130bba23ae47fe2b8e8cddf0195 represents the parent class of various generic Lists. List generics with this wildcard cannot set (set) elements, but can only obtain (get) elements. Because the program cannot determine the types in the List, it cannot add objects. But the object obtained must be of type Object.

The following methods will cause compilation errors:

List<?> list = new ArrayList<>();
 
list.add(new Object());

A few ideas:

1. Listf7e83be87db5cd2d9a8a0b8117b38cd4 objects cannot be used as Lista87fdacec66f0909fc0757c19f2d2b1d objects, that is to say: The Listf7e83be87db5cd2d9a8a0b8117b38cd4 class is not a subclass of the Lista87fdacec66f0909fc0757c19f2d2b1d class.

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 G4ee996100bf04ab273e687539c860625 Not a subtype of Gad40e550a33cb99ea30eede96e03e60e.

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: Listc344555b90c740e0d12635e07ea03035 (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

List41e72a075beaa92298ffb490fa164613 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 List17b25e5edb51071d2fba31bd66af2bfa is not the parent class of Lista6240277e46d54dc29cc58bc214c4982. The first solution is to change the formal parameter List4cfe4bcd4d110814d5bcb5b26c812079 in the getSize method to List6b3d0130bba23ae47fe2b8e8cddf0195, but in this case, forced type conversion is required every time the object is obtained, which is more troublesome. Using the wildcard upper limit solves this problem very well. You can change List4cfe4bcd4d110814d5bcb5b26c812079 to List6418c6233e3d15f72beb2766dfaf6cdc, and the compilation will not be wrong, and no type conversion is required.


Lower limit of wildcard character

List0dfafc26c233a88905402c6a15db8875 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 Listf7e83be87db5cd2d9a8a0b8117b38cd4 type is converted to a List, the type check of the collection elements of the List becomes the upper limit of the type variable (that is, Object). This situation is called erasure.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn