to represent type parameters; 2. Define a generic interface and use Home >Java >javaTutorial >How to use Java generics 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 Java generics are mainly used in the following ways: You can define a generic class, use You can define a generic interface, use You can define a generic method, use When instantiating a generic class or interface, specific type parameters must be specified, for example: You can use wildcards to represent subtypes or supertypes of a certain generic type, including ?, ? extends T and ? super T. , for example: 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: 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!How to use Java generics
public class MyList<T> {
private T[] array;
public MyList(T[] array) {
this.array = array;
}
public T get(int index) {
return array[index];
}
}
public interface MyInterface<T> {
T doSomething();
}
public <T> T doSomething(T param) {
// ...
}
MyList<String> list = new MyList<>(new String[]{"a", "b", "c"});
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});
public <T extends Number> void doSomething(T param) {
// ...
}