JAVA HashSet Order

hashset, java, sorting

Solution

`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`

Problem

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?

Original source

Related problems