Java generics mainly include "define generic classes", "define generic interfaces", "define generic methods", "instantiate generic classes or interfaces", "use wildcards" and "use generics". Six uses of "type qualification": 1. Define a generic class and use
to represent type parameters; 2. Define a generic interface and use to represent type parameters; 3. Define a generic method , use to represent type parameters; 4. When instantiating a generic class or interface, specify specific type parameters; 5. Use wildcards to represent a subtype or supertype of a certain generic type.
Java generics are mainly used in the following ways:
You can define a generic class, use
public class MyList<T> { private T[] array; public MyList(T[] array) { this.array = array; } public T get(int index) { return array[index]; } }
You can define a generic interface, use
public interface MyInterface<T> { T doSomething(); }
You can define a generic method, use
public <T> T doSomething(T param) { // ... }
When instantiating a generic class or interface, specific type parameters must be specified, for example:
MyList<String> list = new MyList<>(new String[]{"a", "b", "c"});
You can use wildcards to represent subtypes or supertypes of a certain generic type, including ?, ? extends T and ? super T. , for example:
MyList<? extends Number> list1 = new MyList<>(new Integer[]{1, 2, 3}); MyList<? super Integer> list2 = new MyList<>(new Number[]{1.0, 2.0, 3.0});
Among them, list1 can accept any type that is a subtype of Number (such as Integer, Float, etc.) as an element, while list2 can accept any type that is a supertype of Integer (such as Number, Object, etc.) as elements.
You can use generic qualification to limit the scope of type parameters, including extends and super, for example:
public <T extends Number> void doSomething(T param) { // ... }
Among them,
The above is the detailed content of How to use Java generics. For more information, please follow other related articles on the PHP Chinese website!