Java HashSet shows list in weird order, always starting with 3

不羁的心 提交于 2019-12-06 05:38:59

The order of return is dependent on an internal hashing algorithm, to which you are supposed to be indifferent. (The idea behind the hashing algorithm is to disperse key values uniformly across an internal table. You probably get 3 back every time since this algorithm is probably deterministic).

If you want things back in lexographic order then use a TreeSet.

To preserve the order of insertion, use a LinkedHashSet.

HashSet doesn't maintain a predictable order, it will depend on the hashCode of the object reference. If you want to maintain the order in which the elements are inserted, use a LinkedHashSet. If you want to maintain the elements always sorted, use a TreeSet.

This is due to the implementation of HashSet. If you would like a Set that sustains some order, you could use a LinkedHashSet instead.

From the LinkedHashSet javadoc:

This implementation spares its clients from the unspecified, generally chaotic ordering provided by HashSet, without incurring the increased cost associated with TreeSet. It can be used to produce a copy of a set that has the same order as the original, regardless of the original set's implementation:

From Oracle documentation we can find the HashSet class implements the set interface and internally backed by Hash Table.It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time.

Hence, I will suggest You to use TreeSet if You care for the order of element.

public static void main(String[] args){
        String version = System.getProperty("java.version");
        System.out.println("JDK version-"+version); 
        SortedSet<String> ss = new TreeSet<String>();
        ss.add("1");
        ss.add("3");
        ss.add("2");
        ss.add("4");
        System.out.println(ss);

    }

o/p:

JDK version-1.6.0
[1, 2, 3, 4]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!