3

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?

ZoeH
  • 109
  • 9
  • 1
    HashSet order (if you want to call it that..) is based on hashCode. So, based on the HashCode of the Objects put to it, the ordering is decided. – TheLostMind Jul 08 '14 at 08:19
  • 3 vote up for duplicated question and 4 for answering to a duplicated question which has already been answered. Interesting :) – Blue Ocean Jul 08 '14 at 09:37

5 Answers5

4

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

Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438
2

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

Kayaman
  • 72,141
  • 5
  • 83
  • 121
0

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

Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
0

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.

Rob Lockwood-Blake
  • 4,688
  • 24
  • 22
0

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.

Bohemian
  • 412,405
  • 93
  • 575
  • 722