Question

Is there a method that comes with HashSet that allows it to sort itself, instead of writing an algorithm to sort it? I know the documentation http://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html has an Iterator, but how is that actually implemented?

Was it helpful?

Solution

HashSet's iterator is not sorted because it just outputs the bins as-is. In fact, changing the implementation of the class, the load factor or any of the other parameters almost always changes the order of the iterator. However, you can wrap the set values in a List and sort them using Collections.sort(List) or Collections.sort(List, Comparator):

import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
...
HashSet<? extends Comparable> myHashSet = ...;
...
List<? extends Comparable> sortedList = Arrays.asList(myHashSet.toArray(new Comparable[0]));
Collections.sort(sortedList);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top