views:

51

answers:

1

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:

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
+1  A: 

In your three examples whats really going on is memory optimisation, because with an empty Collection you are using a subset of the class behaviour, without relying on any which depend on the parameterized type, you can re-use a raw instance.

You could write emptyList() as follows

private static <T> List<T> emptyList() {
    return new EmptyList<T>();
}

The only difference in behaviour would be Collections.emptyList() == Collections.emptyList() would return false.

I'm not sure if this has been named but from a documentation perspective, a comment saying something like "no parameterized behaviour required, so static instance can be re-used" just about covers it.

Jon Freedman