4

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>();
shmosel
  • 49,289
  • 6
  • 73
  • 138
Vinod Jayachandran
  • 3,726
  • 8
  • 51
  • 88
  • 1
    you can use List list = new ArrayList(); If you ought to use String in list this is the generic way. – Anant666 Aug 29 '17 at 05:38
  • public static List createListOfType(Class type) { return new ArrayList(); } Or u can use a flexible method to use one. refer [Here](https://stackoverflow.com/questions/4818228/how-to-instantiate-a-java-util-arraylist-with-generic-class-using-reflection) – Anant666 Aug 29 '17 at 05:41
  • What do you think this would accomplish? Sounds like an [XY Problem](http://xyproblem.info/). – shmosel Aug 29 '17 at 05:51

3 Answers3

2
List<String> objList = new ArrayList<>();

is meant for doing that itself and the List javadoc clearly states that.

Type Parameters:
E - the type of elements in this list
Naman
  • 27,789
  • 26
  • 218
  • 353
1

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

Pritam Banerjee
  • 17,953
  • 10
  • 93
  • 108
1

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.