Index

Appendices

Java Collections

19.1 Common Pitfalls and How to Avoid Them

Java Collections are powerful but can also be tricky. Many beginners and even intermediate developers encounter pitfalls that lead to bugs, unexpected behavior, or performance issues. This section highlights some frequent mistakes and practical ways to avoid them.

Incorrect equals() and hashCode() Implementation

Why it happens: Collections like HashSet, HashMap, and other hash-based structures rely on consistent and correct implementations of equals() and hashCode() to detect duplicates or locate entries.

What goes wrong:

How to avoid:

class Person {
    private final String id;

    Person(String id) {
        this.id = id;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Person)) return false;
        Person other = (Person) o;
        return id.equals(other.id);
    }

    @Override
    public int hashCode() {
        return id.hashCode();
    }
}

Modifying Collections During Iteration

Why it happens: Beginners often try to add or remove elements directly while iterating over a collection.

What goes wrong:

How to avoid:

List<String> list = new ArrayList<>(List.of("a", "b", "c"));
Iterator<String> it = list.iterator();
while (it.hasNext()) {
    String s = it.next();
    if (s.equals("b")) {
        it.remove();  // Safe removal
    }
}

Ignoring Concurrency Issues

Why it happens: Many standard collections like ArrayList and HashMap are not thread-safe. Beginners often share them across threads without synchronization.

What goes wrong:

How to avoid:

Misuse of Generics

Why it happens: Incorrect generic declarations or unchecked casts often lead to runtime exceptions or compiler warnings.

What goes wrong:

How to avoid:

List<String> strings = new ArrayList<>();
strings.add("hello");
// strings.add(123); // Compile-time error, safe

Overusing LinkedList or Vector

Why it happens: Some programmers use legacy collections like Vector or LinkedList without understanding their performance trade-offs.

What goes wrong:

How to avoid:

Summary

By understanding these common pitfalls and following the best practices, you can write safer, more reliable, and performant collection-based code. Careful implementation of equals/hashCode, safe iteration, appropriate concurrency management, and correct generic usage are foundational skills for effective Java development.

Index

19.2 Useful Third-Party Libraries (Guava, Apache Commons Collections)

While Java’s standard Collections Framework is robust and versatile, popular third-party libraries like Google Guava and Apache Commons Collections offer powerful extensions and utilities that greatly simplify and enhance collection handling. These libraries provide advanced data structures, immutable collections, and convenient utilities that address common programming needs beyond what the standard library offers.

Google Guava

Guava is a widely-used, open-source Java library developed by Google that extends Java Collections with rich features and improved APIs.

Key Features:

Example: Using Guava’s Immutable Collections and Multimap

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;

public class GuavaExample {
    public static void main(String[] args) {
        // Creating an immutable list
        ImmutableList<String> colors = ImmutableList.of("red", "green", "blue");
        System.out.println("Immutable colors: " + colors);

        // Using Multimap: one key to many values
        Multimap<String, String> multimap = ArrayListMultimap.create();
        multimap.put("fruit", "apple");
        multimap.put("fruit", "banana");
        multimap.put("vegetable", "carrot");
        System.out.println("Multimap contents: " + multimap);
    }
}

Apache Commons Collections

Apache Commons Collections is another mature library offering a broad set of collection utilities and data structures.

Key Features:

Example: Using Apache Commons Collections’ BidiMap

import org.apache.commons.collections4.bidimap.DualHashBidiMap;

public class CommonsExample {
    public static void main(String[] args) {
        DualHashBidiMap<Integer, String> bidiMap = new DualHashBidiMap<>();
        bidiMap.put(1, "one");
        bidiMap.put(2, "two");

        System.out.println("Key for value 'one': " + bidiMap.getKey("one"));
        System.out.println("Value for key 2: " + bidiMap.get(2));
    }
}

Why Use These Libraries?

Summary

Guava and Apache Commons Collections extend Java’s collection capabilities in ways that enable more efficient, expressive, and safe code. Incorporating these libraries can greatly improve development productivity and the quality of collection-heavy applications.

Index