Sub topic 2
Removing Elements Safely While Iterating
Removing Elements Safely
Say you loop over a list with for-each and call list.remove() inside the loop. Java stops the program with a ConcurrentModificationException. That is an error Java throws when a collection changes while it is being looped over.
There are two safe ways to remove elements during a loop:
- An
Iteratoris an object that walks through a collection one element at a time. Itsremove()method deletes the element it just returned. removeIfis a list method that deletes every element matching a test.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class SafeRemoveDemo {
public static void main(String[] args) {
List<String> words = new ArrayList<>(List.of("apple", "kiwi", "banana", "fig"));
Iterator<String> it = words.iterator();
while (it.hasNext()) {
if (it.next().length() < 4) {
it.remove();
}
}
System.out.println(words); // [apple, kiwi, banana]
words.removeIf(w -> w.startsWith("k"));
System.out.println(words); // [apple, banana]
}
}LinkedList vs ArrayList
A LinkedList is a list where each element links to the next one. An ArrayList stores its elements side by side, like an array. ArrayList reads any index quickly. LinkedList adds and removes at the ends quickly but is slow at get(i). Use ArrayList unless you have a clear reason not to.
How Java Decides Two Objects Are Equal
equals is a method that says whether two objects count as the same. hashCode is a method that returns a number used to find an object quickly. If two objects are equal, they must return the same hash code. If you override one of these methods, override the other as well.
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
public class Point {
private final int x;
private final int y;
public Point(int x, int y) { this.x = x; this.y = y; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Point)) return false;
Point other = (Point) o;
return x == other.x && y == other.y;
}
@Override
public int hashCode() { return Objects.hash(x, y); }
public static void main(String[] args) {
Set<Point> points = new HashSet<>();
points.add(new Point(1, 2));
points.add(new Point(1, 2));
System.out.println(points.size()); // 1
}
}Unique Elements with Set and HashSet
A Set is a collection that holds each element only once. A HashSet is a set that uses hashCode and equals to find elements fast. Its add method returns false if the element is already in the set.
Sorting with Comparable and Comparator
Comparable is an interface that gives a class its natural order, such as A to Z for strings. A Comparator is an object that defines some other order, such as by length.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class SortDemo {
public static void main(String[] args) {
List<String> fruits = new ArrayList<>(List.of("banana", "fig", "apple", "kiwi"));
fruits.sort(Comparator.comparing(String::length));
System.out.println(fruits); // [fig, kiwi, apple, banana]
Set<String> sorted = new TreeSet<>(Comparator.reverseOrder());
sorted.addAll(fruits);
System.out.println(sorted); // [kiwi, fig, banana, apple]
}
}Ordered Sets: LinkedHashSet and TreeSet
| Set | Order of elements |
|---|---|
| `HashSet` | No guaranteed order |
| `LinkedHashSet` | The order you added them |
| `TreeSet` | Sorted, by natural order or a `Comparator` |
Exercise
You add new Point(3, 4) to a HashSet twice. Point does not override equals or hashCode. What does size() return, and why?
Show answer
It returns 2. Without the overrides, Java compares object identity, so two separate objects count as different elements.