<分区>
Java 的 Collections.checked*() api 为我们提供了底层集合的类型安全 View 。但是检查发生在运行时并抛出运行时异常,这可能会影响性能。通过使用泛型集合为这些集合赋予特定类型,可以在编译时强制执行相同的类型检查。那么,在某些情况下,Collections.checked*() 是否比指定类型的泛型集合得分更高?
<分区>
Java 的 Collections.checked*() api 为我们提供了底层集合的类型安全 View 。但是检查发生在运行时并抛出运行时异常,这可能会影响性能。通过使用泛型集合为这些集合赋予特定类型,可以在编译时强制执行相同的类型检查。那么,在某些情况下,Collections.checked*() 是否比指定类型的泛型集合得分更高?
最佳答案
javadoc 解释得很好:
The generics mechanism in the language provides compile-time (static) type checking, but it is possible to defeat this mechanism with unchecked casts. Usually this is not a problem, as the compiler issues warnings on all such unchecked operations. There are, however, times when static type checking alone is not sufficient. For example, suppose a collection is passed to a third-party library and it is imperative that the library code not corrupt the collection by inserting an element of the wrong type.
关于Java Collections.checked*() 与通用集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7011486/