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?
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
HashSet is not an OrderedSet like for example TreeSet, therefore you can't make any assumptions on the order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With