简体   繁体   English

Java中的非泛型集合 - 任何用途?

[英]Non-generic collections in Java - any uses?

是否有任何情况下最好在Java中使用非泛型集合而不是通用集合(或者它们仅为向后兼容性而存在)?

Absolutely not. 绝对不。 In the case in which you can't infer types at declaration time, use a ? 如果您无法在申报时推断类型,请使用? as a type specifier - that's what it is for. 作为类型说明符 - 这就是它的用途。 (There are cases where using ? would restrict you from invoking certain methods, such as List.add() . In such cases, you can find a more restrictive type specifier; Object usually works). (有些情况下使用?会限制你调用某些方法,比如List.add() 。在这种情况下,你可以找到一个限制性更强的类型说明符; Object通常可以工作)。

The non-generic usage is still supported because, technically, there is nothing wrong in not using it; 仍然支持非泛型用法,因为从技术上讲, 使用它是没有错的; you're just going to end up writing more casting instructions and put yourself in a higher risk for ClassCastException 's, but it is technically legitimate as far as the specification is concerned. 你最终将编写更多的转换指令并使自己处于ClassCastException的更高风险之中,但就规范而言,它在技术上是合法的。

Overall, there is no case (that I can think of) where avoiding generics is "better than" using them. 总的来说,没有任何情况(我能想到)避免泛型“比使用它们更好”。 At the worst case (when you must use ? or Object at declaration time), both approaches are equal. 在最坏的情况下(当你必须在声明时使用?Object )时,两种方法都是相同的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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