Junior — Middle
How can a set based on a hash table containing integer values be sorted?
sobes.tech AI
Answer from AI
In Java, a set (Set), based on a hash table, such as HashSet, does not guarantee the order of elements. To sort such integer values, you need to:
- Convert the set to a list (List).
- Sort the list using Collections.sort() or the sort() method of List.
Example:
import java.util.*;
Set<Integer> hashSet = new HashSet<>();
hashSet.add(5);
hashSet.add(1);
hashSet.add(3);
List<Integer> list = new ArrayList<>(hashSet);
Collections.sort(list);
System.out.println(list); // Outputs [1, 3, 5]
Thus, the sorting occurs not in the set itself, but in the list created from it.