TreeSet相关问题
1、TreeSet的底层是二叉树,按照树节点进行存储和取出,所以可以实现排序。
2、TreeSet基于 TreeMap 的 NavigableSet 实现,根据构造方法的不同,选择使用自然排序或者比较器排序。
排序:
自然排序:
采用无参构造,要求对象所属的类实现Comparable接口。
比较器排序:
TreeSet的带参构造,构造方法需要接收一个实现了Comparator接口的对象。
实现案例:
Student s1 = new Student("111","张三",21);
Student s2 = new Student("222","曹曹",20);
Student s3 = new Student("333","孙权",19);
Student s4 = new Student("444","刘备",18);
Student s5 = new Student("555","张飞",19);
Set set = new java.util.TreeSet();
set.add(s1);
set.add(s2);
set.add(s3);
set.add(s4);
set.add(s5);
// 构造迭代器显示结果
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
Student o = (Student) iterator.next();
System.out.println(o.getName());
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Comparable接口 :
Comparable接口强行对实现它的类的每个实例进行自然排序,该接口的唯一方法compareTo方法被称为自然比较方法;强烈建议自然排序和equals一致(就是两个对象调用compareTo方法和调用equals方法返回的布尔值应该一样)
Comparator接口:
Comparator接口强行对某个对象 collection 进行整体排序 的比较函数。可以将 Comparator 传递给 sort 方法
Comparable接口实现案例:
class Dog implements Comparable{
public int age;
public String name;
public Dog(int age,String name){
this.age=age;
this.name=name;
}
@Override
public String toString(){
return "Dog [age="+age+",name="+name+"]";
}
@Override
public int compareTo(Object o) {
Dog d =(Dog)o;
if(this.age>d.age) return 1;
if(this.age<d.age) return -1;
return 0;
}
}
//以下是main方法的内容
List list = new ArrayList();
list.add(new Dog(6,"旺财"));
list.add(new Dog(3,"啊黄"));
list.add(new Dog(5,"伯爵"));
for(int i=0;i<list.size();i++){
System.out.println(list.get(i).toString());
}
Collections.sort(list);
System.out.println("sort排序后");
for(int i=0;i<list.size();i++){
System.out.println(list.get(i).toString());
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
Comparator接口实现案例:
public class ComparatorLength implements Comparator{
@Override
public int compare(String o1, String o2) {
int len1 = o1.length();
int len2 = o2.length();
return (len1 - len2 > 0) ? 1 : -1;
}
}
//以下是main函数
String[] str = {"aadf","dqwd","dqwfcsqc","xqsccaac","csfwffqaf","czxca","cas","cacs","casc"};
Comparator com1 = new ComparatorLength();
Comparator com2 = new ComparatorLength();
Arrays.sort(str, com1);
System.out.println(Arrays.toString(str));
Arrays.sort(str, com2);
System.out.println(Arrays.toString(str));
System.out.println((com1 == com2) +"--"+ (com1.equals(com2)));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19