Home >Java >javaTutorial >The difference between T and question mark (wildcard) in java generics

The difference between T and question mark (wildcard) in java generics

高洛峰
高洛峰Original
2016-12-19 15:43:112273browse

Types originally included: simple types and complex types. After the introduction of generics, complex types are divided into more details;

Now Lista87fdacec66f0909fc0757c19f2d2b1d, Listf7e83be87db5cd2d9a8a0b8117b38cd4 are two different types; and there is no inheritance relationship;

The benefits of generics are:

Start version

 public void write(Integer i, Integer[] ia);  public void write(Double  d, Double[] da);

Generic version

 public <T> void write(T t, T[] ta);

Simplified code

Define generics

1. Define it after the class

Follow the class name

 public class TestClassDefine<T, S extends T>{}

Define generic T, S, and S inherits T

2. It is defined after the method decorator

immediately after the modifier (public)

 public <T, S extends T> T testGenericMethodDefine(T t, S s){}

defines the generic T, S, and S inherits T

instantiates the generic

1. Instantiate a generic defined on a class

when first declaring a class variable or instantiating it. For example

    List<String> list;     list = new ArrayList<String>;

when the second inherited class or implements an interface. For example

public class MyList<E> extends ArrayList<E> implements List<E> {...}

2. Generics on instantiation definition method076402276aae5dbec7f672f8f4e5cc81

When calling a generic method, the compiler automatically assigns a value to the type parameter (generic). When the assignment cannot be successful, a compilation error is reported

Wildcard (?)

There are definitions and assignments of generics above; when assigning values, the above section said that the assigned values ​​are all specific types. When the assigned type is uncertain, we use wildcards (?) instead Now:

Such as

List<?> unknownList;  List<? extends Number> unknownNumberList;  
List<? super Integer> unknownBaseLineIntgerList;

In the Java collection framework, for a container class whose parameter value is of unknown type, you can only read the elements and cannot add elements to it. Because its type is unknown, the compiler cannot recognize the addition. Whether the type of element and the type of container are compatible, the only exception is NULL


For more related articles about the difference between T and question mark (wildcard) in java generics, please pay attention to 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