javaexpert
javaexpert

Reputation: 31

Java HashMap and underlying values() collection

I was wondering if the Collection view of the values contained in a HashMap is kept ordered when the HashMap changes.

For example if I have a HashMap whose values() method returns L={a, b, c} What happened to L if I add a new element "d" to the map? Is it added at the end, i.e. if I iterate through the elements, it's the order kept?

In particular, if the addition of the new element "d" causes a rehash, will the order be kept in L?

Many thanks!

Upvotes: 3

Views: 746

Answers (4)

aioobe
aioobe

Reputation: 421020

I was wondering if the Collection view of the values contained in a HashMap is kept ordered when the HashMap changes.

No, there is no such guarantee.

If this was the case, then the following program would output and ordered sequence from 1-100

HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();

for (int i = 0; i < 100; i++)
    map.put(i, i);

System.out.println(map.values());

(and it doesn't).

There is a class that does precisely what you're asking for, and that is LinkedHashMap:

Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).

Upvotes: 4

Bala R
Bala R

Reputation: 108957

Generally they is no guarantee of order when you are using HashMap. It might be in the order in which you add elements for a few elements but it would get reshuffled when there is a possibility of collision and it has to go with a collision resolution strategy.

Upvotes: 0

TofuBeer
TofuBeer

Reputation: 61526

If it doesn't say it in the JavaDoc then there are no guarantees about it. Different versions of Java could do different things. Don't depend on undocumented behaviour.

You might want to look at LinkedHashMap.

Upvotes: 1

krtek
krtek

Reputation: 26597

HashMap in Java aren't ordered, so I think it will be safe to say that values() won't return an ordered Collection.

LinkedHashMap is an ordered version of HashMap (insertion order), but I don't know it values() will return an ordered Collection. I think the best is to try.

Upvotes: 0

Related Questions