Java Collections.checked*() vs Generic collections [duplicate]
Java's Collections.checked*() api gives us type-safe views to underlying collections. But the checks happen at runtime and throw a runtime exception which can be costly for performance. The same type checking can be enforced at compile time by giving a specific t开发者_Python百科ype to those collections by using generic collections. So are there situations where Collections.checked*() scores over generic collections with their types specified?
The javadoc explains it well:
http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#checkedCollection%28java.util.Collection,%20java.lang.Class%29
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.
The main difference is that the compile-time check can easily be circumvented, both accidentally and consciously.
The compiler will warn you, if that happens, but warnings are easily ignored and the problem might happen in some library somewhere. The type-information provided by generics is reliable, but only if all the code involved compiles without any warnings related to generics: no unchecked casts, no raw types.
Using Collections.checked*()
gives you a way to enforce the restriction, even when using code that's outside of your control (as long as you can pass in a collection of your own).
Collectons.checkedXxxxx() performs runtime checks are provides extra safety. The compiler can be avoided by using type erasure, however the checked collections should always check the type is correct.
I doubt the performance difference is enough to worry about. It is likely to be about 10 ns or less.
When using an old library with unchecked types in a new 1.5+ project.
精彩评论