Generics - Sanjeev435/MyJavaPractiseSets GitHub Wiki

1. Don’t use raw types

  • Using raw types can lead to exceptions at runtime, so don’t use them. They are provided only for compatibility and interoperability with legacy code that predates the introduction of generics

Some Example terms

Term Example
Parameterized type List
Actual type parameter String
Generic type List
Formal type parameter E
Unbounded wildcard type List<?>
Raw type List
Bounded type parameter < E extends Number >
Recursive type bound <T extends Comparable>
Bounded wildcard type List<? extends Number>
Generic method static List asList(E[] a)
Type token String.class

2. Eliminate unchecked warnings

  • Eliminate every unchecked warning that you can. If you eliminate all warnings, you are assured that your code is typesafe, which is a very good thing. It means that you won’t get a ClassCastException at runtime, and it increases your confidence that your program will behave as you intended.

  • If you can’t eliminate a warning, but you can prove that the code that provoked the warning is typesafe, then (and only then) suppress the warning with an @SuppressWarnings("unchecked") annotation.

  • Always use the SuppressWarnings annotation on the smallest scope possible. Typically this will be a variable declaration or a very short method or constructor. Never use SuppressWarnings on an entire class. Doing so could mask critical warnings.

  • It is illegal to put a SuppressWarnings annotation on the return statement, Instead, declare a local variable to hold the return value and annotate its declaration,

  • Unchecked warnings are important. Don’t ignore them. Every unchecked warning represents the potential for a ClassCastException at runtime.


3. Prefer lists to arrays

⚠️ **GitHub.com Fallback** ⚠️