HashSet是无序的,那么如何实习对HashSet进行排序呢?对于这个我们有两种办法了,下面我们一直来看一篇关于java中对HashSet排序的面试题例子。
下面介绍两种方法:
方法一:将HashSet转换为List,然后使用Collections.sort()进行排序
方法二:将将Hashset转换为TreeSet
下面是两种方法的代码:
代码如下 | 复制代码 |
public class HashSetSortingDemo{ public static void main(String args[]) { HashSet names = new HashSet(); names.add("Asker"); names.add("Crak"); names.add("Bayliss"); names.add("Mohna"); names.add("Dina"); System.out.println("HashSet before sorting : " names); //将HashSet转换为List,然后使用Collections.sort()进行排序 List tempList = new ArrayList(names); Collections.sort(tempList); System.out.println("HashSet element in sorted order : " tempList); // 使用TreeSet对HashSet进行排序 TreeSet sorted = new TreeSet(names); System.out.println("HashSet sorted using TreeSet : " sorted); } } |
只是有个问题,既然要排序,那当初干嘛不用LinkedHashSet