Home > Java > javaTutorial > body text

Detailed explanation of generics in Java

高洛峰
Release: 2017-01-18 10:54:11
Original
1365 people have browsed it

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<>();
Copy after login

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
Copy after login

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;
 
}
Copy after login

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());
 
}
Copy after login

Output

true
 
class java.util.ArrayList
 
class java.util.ArrayList
Copy after login

Type wildcard

First of all, it must be clear that if Foo is the parent class of Bar, but List is not the parent class of List. In order to represent various generic parent classes, Java uses "?" to represent generic general Matching. That is, List 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());
Copy after login

A few ideas:

1. List objects cannot be used as List objects, that is to say: The List class is not a subclass of the List 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 G Not a subtype of 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 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); // 这里编译报错
    }
}
Copy after login

The reason for the programming error here is that List< Animal> is not the parent class of List. The first solution is to change the formal parameter List in the getSize method to List, 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 List to List, and the compilation will not be wrong, and no type conversion is required.


Lower limit of wildcard character

List 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:

修饰符 返回值类型 方法名(类形列表){
 
//方法体
 
}
Copy after login

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){ ...}
Copy after login

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 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();  // ③
 
 }
 
}
Copy after login

For more detailed explanations of generics in Java and related articles, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!