How to instantiate generic objects in Java?
In Java, you can instantiate generic objects in the following way:
- brand new
ArrayList<String> list = new ArrayList<String>();
- Can you rephrase this in English?
- fresh
ArrayList<?> list = new ArrayList<>();
- type which is extended
- super type
- fresh
ArrayList<? extends Number> list = new ArrayList<>();
ArrayList<? super String> list = new ArrayList<>();
- Create a generic method: It is possible to define generics within a method and instantiate objects inside the method.
public <T> ArrayList<T> createArrayList() {
return new ArrayList<T>();
}
These are some common ways to instantiate generic objects according to specific needs and usage scenarios.