类型T和对象有什么区别?(What is the difference between type T and Object? [duplicate])

编程入门 行业动态 更新时间:2024-10-24 12:32:22
类型T和对象有什么区别?(What is the difference between type T and Object? [duplicate])

这个问题在这里已经有了答案:

Java泛型T vs Object 7的答案

类型T和对象有什么区别?

换句话说, List<T>和List<Object>之间有什么区别?

This question already has an answer here:

Java generics T vs Object 7 answers

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

更多推荐

本文发布于:2023-07-23 00:46:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1225140.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有什么区别   对象   类型   difference   Object

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!