Effective Java 2nd Edition says that we should not use raw types in new code, and we must also try to eliminate all unchecked casts warnings, and to prove and document its safety if we choose to suppress such a warning.
However, I've repeatedly seen a particular usage that combines raw types and unchecked casts in a type-safe manner. In its most typical form, we have:
- A
static final
field that is declared with a raw type, and refers to an immutable object - A
static
generic method that returns the parameterized version of this field using unchecked cast
The most famous example of this "pattern" are found in java.util.Collections
:
List EMPTY_LIST
and<T> List<T> emptyList()
Set EMPTY_SET
and<T> Set<T> emptySet()
Map EMPTY_MAP
and<K,V> Map<K,V> emptyMap()
The questions are:
- What is this idiom called?
- In which authoritative sources have this idiom been discussed before?
See also
- Effective Java 2nd Edition
- Item 23: Don't use raw types in new code
- Item 24: Eliminate unchecked warnings