Collection Add to Self
ID |
java.collection_add_to_self |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
best-practice, reliability |
Description
Reports calls where a collection adds itself as an element (list.add(list)) or appends its own contents to itself (list.addAll(list)).
Rationale
Adding a collection to itself is almost always a bug:
-
list.add(list)creates a circular reference that causesStackOverflowErrorintoString(),hashCode(), orequals(). -
list.addAll(list)throwsConcurrentModificationExceptionbecause it reads from and writes to the same collection simultaneously.
List<Object> items = new ArrayList<>();
items.add(items); // Circular reference
items.addAll(items); // ConcurrentModificationException
Remediation
Use a different collection or create a copy:
List<Object> items = new ArrayList<>();
List<Object> copy = new ArrayList<>(items);
items.addAll(copy); // Safe: reads from a separate collection