Chapter 7. Effective Generics
This chapter contains advice on how to use generics effectively in practical coding. These items vary in their applicability, from good practice that you should always try to follow, through to techniques that are only to be used as a last resort. Each item is introduced with an indication of where it lies on this scale.
The title of this chapter is an homage to Joshua Bloch’s book, Effective Java (2017).
Note
The code examples for this chapter can be found at:
https://github.com/MauriceNaftalin/JGC_2e_Book_Code/blob/main/src/main/java/org/jgcbook/chapter07
Eliminate Unchecked Warnings
Unchecked warnings are rarely unavoidable. This item describes the unusual situations in which you cannot avoid an unchecked warning, and shows how to handle it in these cases.
We mentioned in “Unchecked Casts” some of the situations in which the compiler is unable to verify that an unchecked warning is unnecessary. Here is another example. The promote method in this code promotes a list of objects to a list of strings, if the list of objects contains only strings, and throws a class cast exception otherwise. The main method is a simplistic test of promote that uses assert statements to show the expected execution path of the program.
Run with assertions enabled, it will not throw an assertion error:
class Promote_1 { public static List<String> promote(List<Object> objs) { for (Object o : objs) if (!(o ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access