Using Generics on right hand side in Java 6?

2019-07-03 18:49发布

I java 6 i can declare the arraylist as follows

Way1: using generics i.e <Integer> on right hand side too

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

Way2: using the diamond operator

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

Way3: using generic only at left side

List<Integer> p = new ArrayList(); 

I prefer to use way 3 as its brief. Is there any difference between these ways? Which one we should prefer and why?

Update:- I know in java 7 second way is recommended but my question is in context of java 6. Which one is preferable?

To me, way 3 also says p is an arraylist of integers (same conveyed by way1). So I find no difference except the fact IDE displays warning message:

ArrayList is a raw type. References to generic type ArrayList<E> should be parameterized

7条回答
淡お忘
2楼-- · 2019-07-03 19:19

Way 3 is not good. Mixing Generics and raw types is naughty, as you are making an assumption for runtime about types, and can run into ClassCastExceptions like the following code:

ArrayList b = new ArrayList();
b.add(5);
ArrayList<String> a = new ArrayList(b);
System.out.println(a.get(0));

So for Java 6, always use way 1

查看更多
祖国的老花朵
3楼-- · 2019-07-03 19:20

Both are same but way2 is available from java 7

查看更多
混吃等死
4楼-- · 2019-07-03 19:20

Both are same .But there are version difference in both of this.

But second way is not possible in java 6.In Java 7 if we not declare type in right side then by default it will take same type as left side.

http://docs.oracle.com/javase/7/docs/technotes/guides/language/type-inference-generic-instance-creation.html

So as per your updates, if you have to use Java 6,then you should use way1.

查看更多
戒情不戒烟
5楼-- · 2019-07-03 19:23

The second way is not possible in Java 6. It is the new way of inferring Generic instance in Java 7.

查看更多
疯言疯语
6楼-- · 2019-07-03 19:31

There is no difference, if you are using java 7 prefer the second method, but is it not available in java 6. It is a new addition to java 7.

查看更多
劳资没心,怎么记你
7楼-- · 2019-07-03 19:40

Way 3 uses raw types. You should never use raw types. They should only be used in legacy code.

查看更多
登录 后发表回答