Java Reference
In-Depth Information
Q UALITY T IP 7.1: Prefer Parameterized Array Lists
Parameterized array lists, such as ArrayList<BankAccount> , were
introduced to the Java language in 2004. Versions of Java prior to version 5.0 had
only an untyped class ArrayList . The untyped array list can hold elements of
any class. (Technically, it holds elements of type Object, the Ȓlowest common
denominatorȓ of all Java classes.) Whenever you retrieve an element from an
untyped array list, the compiler requires you to use a cast:
ArrayList accounts = new ArrayList(); // Untyped
ArrayList
accounts.add(new BankAccount(1729)); // OKȌcan add
any object
BankAccount a = (BankAccount) a.get(0); // Need cast
The cast is needed because the compiler does not keep track of the objects that
were inserted into the array list, and the array list get method has return type
Object .
Untyped array lists are still a part of the Java languageȌafter all, we want to
continue to use programs that were written before 2004. But you should not use
them for new code. The casts are tedious and also a bit error-prone. If you apply
the wrong cast, the compiler cannot detect your mistake. Instead, your program
will throw an exception.
297
298
7.3 Wrappers and Auto-Boxing
Because numbers are not objects in Java, you cannot directly insert them into array
lists. For example, you cannot form an ArrayList<double> . To store sequences
of numbers in an array list, you must turn them into objects by using wrapper classes.
To treat primitive type values as objects, you must use wrapper classes.
There are wrapper classes for all eight primitive types:
Search WWH ::




Custom Search