简体   繁体   中英

Can I use Class in generics?

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>();
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 

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 ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM