Fundamentals 9 min read

Common Java Collection Mistakes and Best Practices

This article explains ten frequent Java pitfalls—including array‑to‑list conversion, containment checks, element removal during iteration, Hashtable vs. HashMap, raw types, access modifiers, List implementations, mutability, constructor issues, and string creation—and provides clear, correct code examples for each.

Java Captain
Java Captain
Java Captain
Common Java Collection Mistakes and Best Practices

1. Converting an array to a List – Arrays.asList() returns a fixed‑size internal list, so to obtain a mutable list you must wrap it in a new ArrayList instance:

List<String> list = Arrays.asList(arr);
ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(arr));

2. Checking whether an array contains a value – instead of converting to a Set, you can directly call Arrays.asList(arr).contains(targetValue) or use a simple for‑each loop:

Set<String> set = new HashSet<String>(Arrays.asList(arr));
return set.contains(targetValue);

Arrays.asList(arr).contains(targetValue);

for(String s : arr){
    if(s.equals(targetValue)){
        return true;
    }
}
return false;

3. Removing elements from a list while iterating – removing by index in a forward loop skips elements; using an Iterator and its remove() method avoids ConcurrentModificationException:

ArrayList<String> list = new ArrayList<String>(Arrays.asList("a","b","c","d"));
for(int i = 0; i < list.size(); i++){
    list.remove(i);
}
System.out.println(list); // prints [b,d]

ArrayList<String> list2 = new ArrayList<String>(Arrays.asList("a","b","c","d"));
for(String s : list2){
    if(s.equals("a")){
        list2.remove(s);
    }
}
// throws ConcurrentModificationException

ArrayList<String> list3 = new ArrayList<String>(Arrays.asList("a","b","c","d"));
Iterator<String> iter = list3.iterator();
while(iter.hasNext()){
    String s = iter.next();
    if(s.equals("a")){
        iter.remove();
    }
}

4. Hashtable vs. HashMap – Hashtable is synchronized, while HashMap is unsynchronized and therefore more commonly used in modern Java code.

5. Using raw types in collections – raw collections bypass generic type checking and can cause ClassCastException. Always prefer parameterised types:

public static void add(List list, Object o){
    list.add(o);
}
public static void main(String[] args){
    List<String> list = new ArrayList<String>();
    add(list, 10);
    String s = list.get(0);
}
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
    at ...

6. Access modifiers – Public fields expose internal state; prefer the lowest reasonable visibility for class members.

7. ArrayList vs. LinkedList – LinkedList performs better for frequent insertions/removals when random access is rare; ArrayList excels at fast random reads.

8. Mutable vs. immutable objects – Immutable objects are safe but may create many temporary instances; mutable objects like StringBuilder are efficient for building large strings:

String result = "";
for(String s : arr){
    result = result + s;
}

Using a mutable builder avoids the overhead of many intermediate immutable strings.

9. Superclass and subclass constructors – If a superclass defines a constructor, the default no‑arg constructor is not generated, leading to compilation errors unless you explicitly add a no‑arg constructor or call super(...) from the subclass:

public Super(){
    System.out.println("Super");
}

Alternatively, remove the custom constructor or invoke super(value) in the subclass.

10. String literals vs. constructors – Literals are interned and compare equal with ==, while new String() creates distinct objects:

// 1. using string literal
String x = "abc";
// 2. using constructor
String y = new String("abc");

String a = "abc";
String b = "abc";
System.out.println(a == b); // true
System.out.println(a.equals(b)); // true
String c = new String("abc");
String d = new String("abc");
System.out.println(c == d); // false
System.out.println(c.equals(d)); // true
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

programmingHashMapArrayList
Java Captain
Written by

Java Captain

Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.