Chapter 1. Introduction
Generics and collections work well with a number of other new features introduced in the latest versions of Java, including boxing and unboxing, a new form of loop, and functions that accept a variable number of arguments. We begin with an example that illustrates all of these. As we shall see, combining them is synergistic: the whole is greater than the sum of its parts.
Taking that as our motto, let’s do something simple with sums: put three numbers into a list and add them together. Here is how to do it in Java with generics:
List<Integer> ints = Arrays.asList(1,2,3);
int s = 0;
for (int n : ints) { s += n; }
assert s == 6;You can probably read this code without much explanation, but let’s
touch on the key features. The interface List and the class Arrays are part of the Collections Framework (both
are found in the package java.util). The
type List is now
generic; you write List<E> to indicate a list with elements of
type E. Here we write List<Integer> to indicate that the elements
of the list belong to the class Integer,
the wrapper class that corresponds to the primitive type int. Boxing and unboxing operations, used to
convert from the primitive type to the wrapper class, are automatically
inserted. The static method asList takes
any number of arguments, places them into an array, and returns a new list
backed by the array. The new loop form, foreach, is used to bind a variable successively to each element of the list, and the loop body adds these into ...
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