Name for a specific type of raw / unchecked cast combo in using Java generics

Effective Java 2nd Edition says that we should not use raw types in the new code, and we should also try to eliminate all unverified throw warnings and prove and document its safety if we decide to suppress such a warning.

However, I have repeatedly seen a specific use that combines raw types and uncontrolled drops in a safe manner. In the most typical form, we have:

  • A static final, which is declared with a raw type and refers to an immutable object
  • A staticgeneric method that returns a parameterized version of this field using an unchecked listing

The most famous example of this "template" is in java.util.Collections:

Questions:

  • What is this idiom called?
  • In which authoritative sources has this idiom been discussed before?

see also

  • Effective Java 2nd Edition
    • Paragraph 23: Do not use raw types in new code
    • Item 24: Clear Unverified Alerts
+3
source share
1 answer

In your three examples, memory optimization actually happens, because with empty Collectionyou use a subset of the class’s behavior, without relying on any that depend on the parameterized type, you can reuse the raw instance.

emptyList()

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

: Collections.emptyList() == Collections.emptyList() false.

, , , , - " , , ", .

+1

Source: https://habr.com/ru/post/1770228/


All Articles