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:

8.2 Mistake 70: Mixing up single object and collection

 

8.3 Mistake 71: Searching for null in a null-hostile collection

 
 
 
 

8.4 Mistake 72: Using null values in maps

 
 
 

8.5 Mistake 73: Trying to modify an unmodifiable Collection

 
 

8.6 Mistake 74: Using mutable objects as keys

 
 
 
 

8.7 Mistake 75: Relying on HashMap and HashSet encounter order

 
 
 

8.8 Mistake 76: Concurrent modification during the iteration

 
 
 

8.9 Mistake 77: Mixing List.remove() overloads

 
 

8.10 Mistake 78: Jumping over the next element after List.remove()

 
 
 
 

8.11 Mistake 79: Reading the collection inside Collection.removeIf()

 
 
 
 

8.12 Mistake 80: Concurrent modification in Map.computeIfAbsent()

 
 
 

Summary

 
 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest