Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 type to those collections by using generic collections. So are there situations where Collections.checked*() scores over generic collections with their types specified?

like image 643
shrini1000 Avatar asked Aug 10 '11 13:08

shrini1000


3 Answers

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.

like image 65
devconsole Avatar answered Nov 18 '22 04:11

devconsole


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

like image 42
Joachim Sauer Avatar answered Nov 18 '22 03:11

Joachim Sauer


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.

like image 2
Peter Lawrey Avatar answered Nov 18 '22 02:11

Peter Lawrey