在 Java 中使用类型化与非类型化ArrayList
有什么区别?
例如,使用 CustomObject
的 ArrayList
:
输入:
ArrayList<CustomObject> typedArray = new ArrayList<>();
typedArray.add(new CustomObject);
或非类型:
ArrayList<> nonTypedArray = new ArrayList<>();
nonTypedArray.add(new CustomObject);
有没有优先选择后者的情况?当 ArrayList
持有不同的数据类型时有什么不同吗? String
、Int
等的 ArrayList?
最佳答案
在第二种方法中,不是强制只添加 CustomObject
而在第一种方法中,否则,您将得到编译错误。
ArrayList<CustomObject> typedArray = new ArrayList<>();
typedArray.add(new CustomObject());
这种方法通常更可取,因为没有机会出现 Class Cast Exception,但在第二种方法中,出现这种情况的可能性很高!!
JavaDocs 对其进行了精美的解释:Why to prefer Generics
- 在编译时进行更强的类型检查。
- 消除 Actor 阵容。
- 使程序员能够实现通用算法。
关于java - 类型化与非类型化 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29600320/