How does item ordering in a HashSet work?

I understand that the order of elements in a HashSet must be arbitrary. But out of curiosity, can someone tell me exactly how the order is determined?

I noticed that when I insert two elements (say, A and B), the order will come out A, B, and then re-executing the same code will give me B, A, and then re-eliminating it the third time would give me A, B.

I mean, this is not deterministic, but a bit strange.

+4
source share
4 answers

The order is determined by the Hash algorithm used in the Hash Map / Set, the exact settings of this Map and Hashcodes objects.

- (, ) , . , .

HashMap : http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/HashMap.java

:

; , , .

, , API , !

" " HashMap - , . , LinkedHashMap TreeMap. , , HashMap , - !

+4

:

  • Hashcode , , hashCode ,

  • HashSet , HashMap.initHashSeedAsNeeded (HashSet HashMap SDK Oracle ), sun.misc.Hashing.randomHashSeed(this) hashSeed, hashCode

. , javadoc hashSeed:

/**   * , ,
  * - , -. 0,
  * .  */

+2

( ), / - HashSet.

hashtable. hashCode() , -.

:

- 10, B hashCode 11. hastable 2. - - , - [0], [1].

table[0] = { A }
table[1] = { B }

, , A, B. , .

C hashCode 12 ( ) # 0.

table[0] = { A, C }
table[1] = { B }

, A, C, B. , A C: C, A, B

. . , 2

table[0] = { C }
table[1] = {   }
table[2] = { A }
table[3] = { B }

, 1 .

+1

HashSet garatuees , ( hashCode() Java?)! ! Deserialize , .

LinkedHashSet HashSet.

0

All Articles