Is map/collection order stable between calls?

Posted by John on Stack Overflow See other posts from Stack Overflow or by John
Published on 2010-06-01T22:48:00Z Indexed on 2010/06/01 22:53 UTC
Read the original article Hit count: 143

Filed under:
|
|

If I have a hash map and iterate over the objects repeatedly, is it correct that I'm not guaranteed the same order for every call? For example, could the following print two lines that differ from each other:

Map<String,Integer> map = new HashMap<String,Integer>()
  {{ put("a", 1); put("b", 2); put("c", 3); }};
System.out.println(map);
System.out.println(map);

And is this the case for sets and collections in general? If so, what's the best way in case you have to iterate twice over the same collection in the same order (regardless of what order that is)? I guess converting to a list.

© Stack Overflow or respective owner

Related posts about java

Related posts about collections