Chapter 1. Introduction
The purpose of generics is to allow the same code to be reused for creating or handling objects of different types. For example, List<String> and List<Integer> are different types, but generics allows them to be implemented with the same code, with type safety preventing any possibility of confusion between them. Two kinds of Java code can be generic: types, such as the collection classes and interfaces; and methods, such as the static methods in the utility class java.util.Collections. Let’s look at each of these in turn.
Note
The code examples for this chapter can be found at:
https://github.com/MauriceNaftalin/JGC_2e_Book_Code/tree/main/src/main/java/org/jgcbook/chapter01
Generic Types
An interface or class may be declared to take one or more type parameters, which are written in angle brackets and must be supplied when you declare a variable belonging to the interface or class or when you create a new instance of a class.
Here is an example:1
List<String>words = new ArrayList<String>();words.add("Hello "); words.add("world!"); String s = words.get(0)+words.get(1);
assert s.equals("Hello world!");
In the Collections Framework, the class ArrayList<E> implements the interface List<E>, where E is a
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