I need an example on how to use a comparable class on a HashSet to get an ascending order. Let’s say I have a HashSet like this one:
HashSet<String> hs = new HashSet<String>();
How can I get hs to be in ascending order?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Use a
TreeSetinstead. It has a constructor taking aComparator. It will automatically sort theSet.If you want to convert a
HashSetto aTreeSet, then do so:If the items you have itself already implements
Comparableand its default ordering order is already what you want, then you basically don’t need to supply aComparator. You could then construct theTreeSetdirectly based on theHashSet. E.g.See also: