今天面试问到Set集合实现有序的问题,发现集合这部分知识要补一补....
以下所有api描述来源:https://docs.oracle.com/javase/7/docs/api/
实现Set接口的类如下,其中最常见的HashSet和TreeSet。
Interface Set<E>
-
-
All Known Implementing Classes:
- AbstractSet, ConcurrentSkipListSet, CopyOnWriteArraySet, EnumSet, HashSet, JobStateReasons, LinkedHashSet, TreeSet
其中,TreeSet的构造方法如下:
Constructor and Description |
---|
TreeSet()
Constructs a new, empty tree set, sorted according to the natural ordering of its elements.
|
TreeSet(Collection<? extends E> c)
Constructs a new tree set containing the elements in the specified collection, sorted according to the
natural ordering of its elements.
|
TreeSet(Comparator<? super E> comparator)
Constructs a new, empty tree set, sorted according to the specified comparator.
|
TreeSet(SortedSet<E> s)
Constructs a new tree set containing the same elements and using the same ordering as the specified sorted set.
|
TreeSet提供了一个参数为Colleciton的构造方法,利用提供的集合的所有元素进行自然排序后构造一个新的TreeSet集合。
该方法详细描述:
Constructs a new tree set containing the elements in the specified collection, sorted according to the
natural ordering of its elements. All elements inserted into the set must implement the
Comparable
interface. Furthermore, all such elements must be
mutually comparable:
e1.compareTo(e2)
must not throw a
ClassCastException
for any elements
e1
and
e2
in the set.
-
Parameters:
-
c
- collection whose elements will comprise the new set
Throws:
-
ClassCastException
- if the elements inc
are notComparable
, or are not mutually comparable -
NullPointerException
- if the specified collection is null
需要注意的是:1.所有插入set的元素都要实现Comparable接口,即可自然排序。
2.任意两个元素之间都是可以相互比较并且不会抛出类型转换异常,也就是类型一致。
综上,实现Set集合排序,可以通过直接使用TreeSet储存,或者将要实现排序的集合作为参数构造新TreeSet集合,得到的TreeSet集合就是有序集合了。
写个类测试一下...
假设现在有无序的HashSet集合装有若干Sort类型元素,要把元素按value值的大小排序。那么我在Sort类中实现Comparable接口,然后将该HashSet集合作为参数构造新的TreeSet即可得到有序的Set集合。
代码:
import java.util.HashSet;
import java.util.TreeSet;
public class Sort implements Comparable<Sort>{
//排序依据
private Integer value;
//有参构造
public Sort(Integer value){
this.value = value;
}
@Override
public int compareTo(Sort o) {
//正序
return this.value-o.value;
}
@Override
public String toString() {
return value+"";
}
public static void main(String[] args) {
HashSet<Sort> set = new HashSet<Sort>();
//生成数据
for(int i=0; i<16; i+=2){
set.add(new Sort(i));
}
//利用HashSet中的元素通过元素的自然排序构造一个新TreeSet
TreeSet treeSet = new TreeSet(set);
//打印结果
System.out.println("HashSet:"+set);
System.out.println("TreeSet:"+treeSet);
}
}
控制台输出:
HashSet:[12, 4, 10, 8, 14, 0, 2, 6]
TreeSet:[0, 2, 4, 6, 8, 10, 12, 14]