Can I use a class in generics?

If I know the data type for the runtime of an array list, can I use it in generics?

For example, can I use a class (say String.class) while declaring an array list below.

List objList = new ArrayList<DestinationClassToBeReplaced>();
+4
source share
3 answers
List<String> objList = new ArrayList<>();

designed for this, and Listjavadoc clearly states that.

Type Parameters:
E - the type of elements in this list
+2
source

You can write like this:

List<DestinationClassToBeReplaced> objList = new ArrayList<>();

The operator <>is called the Diamond operator.

The above code infers the parameter type of an instance of a typical class using JDK 7 Diamond Operator

+1
source

:

Method 1: use common elements, i.e. on both sides

List<Integer> list = new ArrayList<Integer>();

Method 2: use the common on the left side and the diamond operator on the right side

List<Integer> list = new ArrayList<>();

Method 3: use the common on the left side only

List<Integer> list = new ArrayList(); 

Of the above three methods was introduced in java 7.

If you want to use generics, you must specify the type on the left for it to work. Note that the generic type restriction is chosen by the compiler after checking it at compile time.

Adding a generic only on the right will be inappropriate to you.

+1
source

Source: https://habr.com/ru/post/1684645/


All Articles