Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

java - Why HashSet order always same for my program?

For some tutorial, they said:

HashSet doesn’t maintain any order, the elements would be returned in any random order.

But I write a test program, the result is always same.

import java.util.*;

public class HashSetDemo {

    public static void main(String[] args) {
        HashSet<String> hs1 = new HashSet<String>();
        hs1.add("a");
        hs1.add("b");
        hs1.add("c");
        hs1.add("d");
        hs1.add(null);
        hs1.add(null);
        System.out.println(hs1);
        System.out.println(hs1);
    }
}

Output:

[null, a, b, c, d]
[null, a, b, c, d]

I tried many times, but the order is always same. Why? Hope someone can help me, Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 Strings 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 Strings.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...