Are HashMap entries always sorted by key if the key is of type Integer?

I am looking for an implementation that automatically sorts its records by key. I found an implementation TreeMapthat does this correctly. However, in the tests I created, I found that entries in HashMapare sorted by their key, if the key is of type Integer, by default. Can I assume that it HashMapworks (and continues to work) like this, and uses it safely, or should I use it TreeMapfor this purpose?

+4
source share
1 answer

No, you cannot assume that entries in HashMapare sorted by their key, since that is not the case.

, Integer, , -, , hashCode of Integer - int, 1 1, 2 bin 2 .. , , , , .

Integer, , .

:

:

HashMap<Integer,String> map = new HashMap<> ();
for (int i=0;i<10;i++) {
  map.put (i, Integer.toString (i));
}
for (Integer key : map.keySet ()) {
  System.out.println (key);
}

:

0
1
2
3
4
5
6
7
8
9

:

HashMap<Integer,String> map = new HashMap<> ();
for (int i=0;i<10;i++) {
  map.put (i*100, Integer.toString (i));
}
for (Integer key : map.keySet ()) {
  System.out.println (key);
}

:

0
400
800
100
500
900
200
600
300
700
+7

Source: https://habr.com/ru/post/1676753/


All Articles