The reason for this behaviour is that a HashSet
is backed by a HashMap
, which in turn is backed by an array
of Entry
-objects. where the hash
is used to find the index
of the array
. So there is always an order of elements in a HashSet
(the order of the array
), you just don't have any guarantees as to what this order is.
As far as I can tell from the code, the order of the HashSet
is determined (or at least affected) by the order of the computed hashes
of its elements. Then, with relatively simple inputs (like your single character string), one might assume that there is a strict ordering of the hashes
, which will give you what seems to be a natural ordering. With more complex objects, and thus more complex hash
computations, the hashes
will be more spread, and the ordering "more random".
Also, like it's been pointed out, "no guarantee of ordering" does not imply "guaranteed random ordering".
The hashcode
-method of the String
class also comes into play here, for single character String
s the hashcode
will just be the int
value of the one char
in the String
. And since char
's int
values are ordered alphabetically, so will the computed hashes
of single char
String
s.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…