Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the same Map.Entry change when calling iterator.remove() in Java TreeMap?

Tags:

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().

like image 819
maplemaple Avatar asked Jun 25 '21 17:06

maplemaple


People also ask

Can you iterate through a TreeMap?

The TreeMap in Java is used to implement Map interface and NavigableMap along with the Abstract Class. We cannot iterate a TreeMap directly using iterators, because TreeMap is not a Collection.

Can we add a new entry to HashMap while iterating?

How to add new entry while iterating? Create a new Map<String, String> foo instance and set the desired values there. At the end of your process, assign this map to your old map by using map = foo; .

Can we use iterator in map?

Remember that we cannot iterate over map directly using iterators, because Map interface is not the part of Collection. All maps in Java implements Map interface. There are following types of maps in Java: HashMap.

What is floorEntry in TreeMap?

floorEntry. Returns a key-value mapping associated with the greatest key less than or equal to the given key, or null if there is no such key.


1 Answers

To be clear from Javadoc Map.Entry

The behavior of a map entry is undefined if the backing map has been modified after the entry was returned by the iterator, except through the setValue operation on the map entry

And from Map.Entry.getValue()

Returns the value corresponding to this entry. If the mapping has been removed from the backing map (by the iterator's remove operation), the results of this call are undefined

That means Java doesn't give guarantee that what happens if you call entry after remove method and it's undefined.

like image 84
Vinay Hegde Avatar answered Sep 23 '22 09:09

Vinay Hegde