When I use Iterator
to iterate some TreeMap
, I found the same Map.Entry
's content will change. For example:
import java.util.Map.Entry;
import java.util.TreeMap;
public class Solution {
public static void main(String[] args) {
TreeMap<Integer, Integer> map = new TreeMap<>();
map.put(1,1);
map.put(2,2);
map.put(3,3);
System.out.println("map: " + map);
Map<Integer, Integer> fromMap = map.tailMap(2);
System.out.println("fromMap: " + fromMap);
Iterator<Entry<Integer, Integer>> iter = fromMap.entrySet().iterator();
Entry<Integer, Integer> entry = iter.next();
System.out.println(entry); // line 1
iter.remove();
System.out.println(entry); // line 2. Why does entry content change?
}
}
result:
map: {1=1, 2=2, 3=3}
fromMap: {2=2, 3=3}
2=2
3=3
The entry
in line 1 and line 2 of the above code has the same reference, however the content changes when I call iter.remove()
.
Entry
, rather you should copy its content to some holder class and work on it. – KiangsiMap.Entry
is to useMap.Entry.copyOf()
, new in JDK 17. – Vicarage