8 Collections and maps
This chapter covers
- Common mistakes when adding or looking for an element of unrelated type in a collection
- Handling nulls in collections and maps
- Modifiable and unmodifiable collections
- Concurrent modification of collections
- Problems using the
List.remove()
method - How to implement iterators properly
The Java Collection API appeared long ago in Java 1.2. The world was quite different then: Java had no parameterized types (generics), mutable objects were in favor, and nulls were generally accepted values. Over time, the language and the way people write programs has changed significantly. Yet with all that change, the old collection API remains ubiquitous in modern programs. Some outdated design decisions negatively affect the programming style today and may be the source of bugs.
8.1 Mistake 69: Searching the object of unrelated type
Before parameterized types were introduced to Java, collection and map elements could not be typed as anything more specific than Object
, so you could easily add a string to a list of numbers. When generics were introduced, all methods that add elements to collections were restricted to accept only the collection element type. However, most of the methods that search and remove elements weren’t restricted. This includes the following methods, which operate on individual elements: