0

Suppose that I have a HashMap() defined and allocated like this:

private HashMap<Integer, Integer> rankCombinator=new HashMap<>();

I am always "building" the HashMap with keys and values before accessing it, for example I am storing 15 Integers on it as keys with their corresponding values I want. I am trying to traverse this map using a for-each loop:

for(Map.Entry<Integer, Integer> entry : rankCombinator.entrySet())
{
   // More code here.
}

I suppose this loop won't return the values sorted in the way they were inputted in the the first place. Am I right? If yes, is there any pattern in the values returned? I have tried looking over the documentation but it doesn't seem like it includes a pattern for this.

Theocharis K.
  • 1,281
  • 1
  • 16
  • 43

4 Answers4

4

The HashMap implementation makes no guarantees about the order the items are returned, I would suggest using a LinkedHashMap which retains order.

private Map<Integer, Integer> rankCombinator=new LinkedHashMap<Integer, Integer>();

Api Documentation

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
  • Oh I didn't notice that, I was only aware of the linked lists. Thanks for pointing that out. Do you happen to have an answer to my question as well about the pattern? Out of curiosity mostly... – Theocharis K. Jan 25 '13 at 01:46
  • The HashMap implementation makes no guarantees about the order of items returned. So there really is no pattern. – Kevin Bowersox Jan 25 '13 at 01:49
1

Short answer, no. From the javadoc: "This class makes no guarantees as to the order of the map"

It's arbitrary depending on the number of buckets in the hash table, and the order of elements in the buckets. As such it varies when a rehash happens.

Use a LinkedHashMap if you need predictable order based on insertion order.

sharakan
  • 6,821
  • 1
  • 34
  • 61
1

Hash maps store items in "buckets" based on the hash code of the key. The "plain" HashMap returns entries as it finds them in its "hash buckets". There is no discernable pattern to it, and even if you find it, it would be heavily dependent on implementation and unreliable.

If you need a reliable order of iteration, use either a TreeMap (you'll get entries sorted by key) or LinkedHashMap (you'll get insertion order). Note that the TreeMap has a different mechanism of deciding the equality of its keys, so you would either make the keys comparable, or provide a comparator on the side to deal with the key ordering.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

The order is random, but is determined by the hash function which allocates objects to slots in the hashmap array store.

More on that here: How does a hash table work?

Community
  • 1
  • 1
Tom Carchrae
  • 6,398
  • 2
  • 37
  • 36