A for-each loop over a collection runs on an Iterator (hasNext(), next()). An ArrayList counts its adds and removes; an iterator records the count when created, and next() throws ConcurrentModificationException if it changed. The check is best effort: a bug alarm, not program logic. Iterator.remove() updates the record, so it deletes safely. List.of(...) makes a fixed list, copied here into an ArrayList.
import java.util.*;
public class RemoveDemo {
public static void main(String[] args) {
List<Integer> b = new ArrayList<>(List.of(1, 2, 3, 4));
for (Iterator<Integer> it = b.iterator(); it.hasNext(); )
if (it.next() == 2) it.remove();
System.out.println(b); // [1, 3, 4]
for (Integer x : b) if (x == 1) b.remove(x); // throws ConcurrentModificationException
}
}
A HashMap keeps an array of m buckets. Each bucket holds a chain: the entries whose keys landed there, one after another. A lookup picks the bucket from hashCode, then walks its chain, calling equals only on entries with the same hash code. So equal keys with different hash codes never meet equals, and the lookup fails.
THE EQUALS AND HASHCODE CONTRACT
a.equals(b)⇒a.hashCode()=b.hashCode()
Holds for any two objects a and b. Equal objects must give equal hash codes, so they reach one bucket. Unequal objects may share a hash code. Override both, from the same fields.
o instanceof Point p tests the type and names the cast result p.
import java.util.*;
public class Point {
final int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
@Override public boolean equals(Object o) {
return o instanceof Point p && p.x == x && p.y == y;
}
@Override public int hashCode() { return Objects.hash(x, y); }
public static void main(String[] args) {
Map<Point, String> m = new HashMap<>();
m.put(new Point(1, 2), "A");
System.out.println(m.get(new Point(1, 2))); // A
}
}
Remove hashCode and the two points normally get different identity-based hash codes, so get prints null.
WORKED EXAMPLE
A HashMap has 16 buckets. You put "Aa" (value 1), then "BB" (value 2), then call get("BB"). A two-character string's hashCode is s[0]·31 + s[1], with character codes A = 65, B = 66, a = 97. Which bucket is used, and how many stored keys does get check?
▸ Solution
Hash of "Aa": 65 · 31 + 97 = 2015 + 97 = 2112. Hash of "BB": 66 · 31 + 66 = 2046 + 66 = 2112. They are equal.
2112 lies between 0 and 65536, so the bucket formula applies: i = 2112 mod 16 = 0, since 16 · 132 = 2112. Both keys use bucket 0.
put("BB") meets "Aa" in bucket 0 with the same hash, so equals runs, returns false, and "BB" joins the chain after "Aa".
get("BB") walks bucket 0's chain in order: "Aa" (same hash, not equal), then "BB" (equal), and returns 2: 2 keys checked.
Answer: Bucket 0, with 2 keys checked. Equal hash codes only choose the bucket. equals decides which entry is the key.