100 Java Mistakes and How to Avoid Them

Collections and maps


  • When looking for a specific element in a collection, it’s possible to mistakenly specify an element of unrelated type. In this case, instead of an exception, you’ll just get a not-found result, so the program may silently work incorrectly. 
  • Avoid using types like List<Object>, as the compiler won’t protect you from storing irrelevant elements in such collections. 
  • Collections have inconsistent rules about handling null elements. It’s better to avoid storing and querying nulls at all. 
  • Some Java collections are mutable, while others are not. Mutable collections may not support all mutation operations. The standard Java library does not provide explicit types to designate whether a collection is mutable, so it’s possible to accidentally call the mutation method on an immutable collection, causing an exception at run time. 
  • Sets and maps may rely on the fact that the hashCode() and compareTo() methods produce a stable result for the keys. If the key is modified while it’s stored inside the collection, you may not be able to find this key again. 
  • Some sets and maps may not guarantee any iteration order. It’s important to avoid exposing the internal order to a user interface and to not rely on it in tests. 
  • The List.remove() method has two overloads: it can remove a given element or remove by index. It’s possible to accidentally call the wrong method, especially if you have List<Integer>. Care should also be taken if you remove several elements by index in a loop, as you may accidentally skip some elements. 
  • When iterating over a mutable collection or using collection methods that accept a lambda function, it’s usually not allowed to modify the collection from within the iteration or the lambda function. If you try to, you may get ConcurrentModificationException. 
  • When you implement a custom iterator, it’s essential to fulfill its contract. The standard for–eachloop utilizes only one iterator-usage scenario, so it may work correctly even with a broken iterator. However, other scenarios in which the mistake will show up are possible as well.

#Booksummary

Credit : Manning


To view or add a comment, sign in

Insights from the community

Others also viewed

Explore topics