If I know the data type for an array list run time, can I use it in generics ?
For example, Can I use Class (say String.class
) during declaration of an array list below.
List objList = new ArrayList<DestinationClassToBeReplaced>();
If I know the data type for an array list run time, can I use it in generics ?
For example, Can I use Class (say String.class
) during declaration of an array list below.
List objList = new ArrayList<DestinationClassToBeReplaced>();
You can write like this:
List<DestinationClassToBeReplaced> objList = new ArrayList<>();
The <>
operator is called the Diamond operator.
The above code is inferring generic class's instantiation parameter type with JDK 7's Diamond Operator
Three ways can be used to declare generic lists
Method 1: use generics i.e. on both sides
List<Integer> list = new ArrayList<Integer>();
Method 2: using generic on the left and the diamond operator on the right side
List<Integer> list = new ArrayList<>();
Method 3: using generic only at left side
List<Integer> list = new ArrayList();
Of the above three the second method was introduced in java 7.
If you want to use generics you must specify type on the left for it to work. Note that the type restriction of generics is thrown away by compiler after checking it during compilation.
Adding generic only on the right will serve you no purpose.