Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA HashSet Order [duplicate]

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?

like image 858
ZoeH Avatar asked Sep 14 '26 13:09

ZoeH


2 Answers

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

like image 188
jmj Avatar answered Sep 16 '26 07:09

jmj


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

like image 35
Kayaman Avatar answered Sep 16 '26 07:09

Kayaman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!