JAVA HashSet Order [duplicate]

倾然丶 夕夏残阳落幕 提交于 2020-04-06 13:21:30

问题


this is my code on one exercise,

public class RockTest {
public static void main(String[] args){
    HashSet<Rock> hashset = new HashSet();
    Rock rock1 = new Rock("QingDanasty",89);
    Rock rock2 = new Rock("Modern",32);
    Rock rock3 = new Rock("MingDanasty",100);

    hashset.add(rock1);
    hashset.add(rock2);
    hashset.add(rock3);

    Iterator<Rock> iterator = hashset.iterator();
    while(iterator.hasNext()){
        System.out.println(iterator.next().getName());
    }
}
}

When the code gets printed, the console shows the order of rock2 rock1 rock3 instead of rock1 rock2 and rock3 ,however, I wonder why?


回答1:


HashSet doesn't preserve order, if you want it to preserve order of insertion use LinkedHashSet instead

if you want it to preserve some comparative order then use custom Comparator and TreeSet




回答2:


HashSet is not an OrderedSet like for example TreeSet, therefore you can't make any assumptions on the order.




回答3:


HashSet not grantee the insertion order. you can use TreeSet or LinkHashSet if you are concern about the insertion order.




回答4:


As the other answers have pointed out, it is because you are using a Set to store your objects (in your case a HashSet in particular). Sets do not guarantee ordering of items added to them, this is why you see them printed out in a different order to how you added them. If you want to maintain ordering of elements added to a Collection, then you probably need to use a List such as LinkedList or ArrayList.

Rather than just leaving you at that, I'll point you in the direction of the Java trail on the different Collection types within the language. What the trail will help you understand is when to use the different types of Collection implementation that Java provides and what are the characteristics of each collection type.




回答5:


For a HashSet, iteration order is based on the hashCode of each element, which is more or less "random" (although determinant for instances of some classes).

To have iteration order match the insertion order, use a LinkedHashSet whose iteration order is the same as insertion order, or an implementation of SortedSet such as TreeSet, which sorts its elements based on their natural order (if they inplement Comparable) or using a supplied Comparator.



来源:https://stackoverflow.com/questions/24626880/java-hashset-order

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