这个问题在这里已经有了答案:
Java泛型T vs Object 7的答案类型T和对象有什么区别?
换句话说, List<T>和List<Object>之间有什么区别?
This question already has an answer here:
Java generics T vs Object 7 answersWhat is the difference between type T and Object ?
In other words what is the difference between between List<T> and List<Object>?
最满意答案
在运行时,没有什么区别:Java泛型是通过Type Erasure实现的,因此所有实现中都使用相同的类。
然而,在编译时,差异是巨大的,因为它可以避免每次使用对象时进行投射,使代码看起来更清晰。
考虑这个例子:
List<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(2); list.add(3); for (Integer n : list) { System.out.println(n+5); }这编译和运行良好,而且它也易于阅读。 如果您想使用List<Object> ,代码看起来不会很干净:
List<Object> list = new ArrayList<Object>(); list.add(1); list.add(2); list.add(3); for (Object o : list) { // Now an explicit cast is required Integer n = (Integer)o; System.out.println(n+5); }但是,在内部,这两个代码片段对其list对象使用相同的确切实现。
At runtime, there is no difference: Java generics are implemented through Type Erasure, so the same class is used in all implementations.
At compile time, however, the difference is enormous, because it lets you avoid casting every time that you use an object, making you code look a lot cleaner.
Consider this example:
List<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(2); list.add(3); for (Integer n : list) { System.out.println(n+5); }This compiles and runs well, and it also easy to read. If you wanted to use List<Object> instead, the code would not look as clean:
List<Object> list = new ArrayList<Object>(); list.add(1); list.add(2); list.add(3); for (Object o : list) { // Now an explicit cast is required Integer n = (Integer)o; System.out.println(n+5); }Internally, though, the two code snippets use the same exact implementation for their list object.
更多推荐
发布评论