集合框架--7
TreeSet的Comparator排序 TreeSet总结
----------- android培训、java培训、java学习型技术博客、期待与您交流! ------------
1. TreeSet的Comparator排序
1). Comparator应用的背景
如果对象元素不具有比较性 (就是存入集合的元素所在的类本身没有实现Comparable接口)或者对象元素自身的比较性不符合需求(也就是不符合需求中的排序规则)。并且集合中的元素类不能被修改。此时就要使用Comparator这个接口来达到所需的排序功能。
2). Comparator的使用方式
(1). TreeSet的构造方法
[1]. public TreeSet()
构造一个空参的TreeSet。这个TreeSet根据自然顺序(默认的顺序)进行排序
[2]. public TreeSet(Comparator<?super E>comparator)
构造一个TreeSet。这个TreeSet根据Comparator比较器中的规则进行排序
(2). Comparator接口介绍
public interface Comparator<T> {
int compare(T o1, T o2);
boolean equals(Object obj);
}
(3). 示例代码的普通写法
【示例代码】学生姓名先排序,如果姓名相同,按照年龄排序
class MyComparator implements Comparator{
public int compare(Object o1, Object o2){
if(!((o1 instanceof Student)&&(o2 instanceof Student))){
throw new RuntimeException("Sorry");
}
Students1 =(Student)o1;
Students2 =(Student)o2;
int num =s1.getName().compareTo(s2.getName());
if(num ==0)
return s1.getAge() -s2.getAge();
return num;
}
}
class TreeSetDemoII{
public static void sop(Object o){
System.out.println(o);
}
public static void main(String[] args){
TreeSetts =new TreeSet(new MyComparator());
ts.add(new Student("lisi02", 22));
ts.add(new Student("lisi007", 20));
ts.add(new Student("lisi09", 19));
ts.add(new Student("lisi09", 18));
Iteratorit =ts.iterator();
while(it.hasNext()){
sop(it.next());
}
}
}
打印结果:
(4). 示例代码的匿名内部类写法
class TreeSetDemoIII{
public static void sop(Object o){
System.out.println(o);
}
public static void main(String[] args){
TreeSetts =new TreeSet(new Comparator(){
@Override
public int compare(Object o1, Object o2) {
if(!(o1 instanceof Student && o2 instanceof Student))
throw new RuntimeException("非法输入");
Students1 =(Student)o1;
Students2 =(Student)o2;
int nameDifference=s1.getName().compareTo(s2.getName());
if(nameDifference ==0)
return s1.getAge() -s2.getAge();
return nameDifference;
}
});
ts.add(new Student("lisi02", 22));
ts.add(new Student("lisi007", 20));
ts.add(new Student("lisi09", 19));
ts.add(new Student("lisi09", 18));
Iteratorit =ts.iterator();
while(it.hasNext()){
sop(it.next());
}
}
}
打印结果:
【比较优先级】当元素和容器本身都具有比较性的时候,容器比较器优先
这里面Student类和TreeSet容器都具有比较性,Student是age主条件----age相同,比较name
容器本身是:name主条件----name相同,比较age
返回的排序结果就是容器比较性的排序。
2. TreeSet总结
1). TreeSet的特点
(1). 可以对元素进行排序
有两种排序方式。
(2). TreeSet保证元素的唯一性依据
在实现的Comparable的compareTo或者Comparator的compare方法中,如果这两个方法的返回值为0,那么TreeSet就认为这两个元素一样。按照Set的唯一性规则,在一次重复的元素不能被添加到TreeSet这个集合中。
2). TreeSet的两种排序方式
(1). 让元素本身具有比较性
元素本身要实现Comparable接口并实现里面的compareTo方法以保证元素本身具有比较性
(2). 让容器自身具有比较性
当元素本身不具有比较性或者具备的比较性不是所需要的,就在TreeSet建立实例的时候,传入Comparator接口的实现子类的实例。这个Comparator子类必须实现compare方法。
(3). 元素的可存储性
[1]. 自定义的类,如果重写了hashCode和equals两个方法,可以存入HashSet容器
[2]. 自定义的类,如果实现了Comparable的compareTo()方法,可以存入TreeSet容器。
【总结】如果 自定义的类既重写了 hashCode和 equals, 又实现了 compareTo,那么这个类的元素 既可以存入HashSet容器, 也可以存入 TreeSet容器。----------- android培训、java培训、java学习型技术博客、期待与您交流! ------------