—另可参见大神博客http://blog.csdn.net/benjaminzhang666/article/details/9471763
——————————————————————————————————————————————
TreeSet的两种排序方式
(1). 让元素本身具有比较性
(2). 让容器自身具有比较性
(3). 元素的可存储性
[1]. 自定义的类,如果重写了hashCode和equals两个方法,可以存入HashSet容器
[2]. 自定义的类,如果实现了Comparable的compareTo()方法,可以存入TreeSet容器。
【总结】如果自定义的类既重写了hashCode和equals,又实现了compareTo,那么这个类的元素既可以存入HashSet容器,也可以存入TreeSet容器。
【比较优先级】当元素和容器本身都具有比较性的时候,容器比较器优先
——————————————————————————————————————————————
1). Comparator应用的背景
如果对象元素不具有比较性
2). Comparator的使用方式
(1). TreeSet的构造方法
[1].
构造一个空参的TreeSet。这个TreeSet根据自然顺序(默认的顺序)进行排序
[2].
(2). Comparator接口介绍
public
}
(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()); -
} -
} - }
打印结果:
【比较优先级】当元素和容器本身都具有比较性的时候,容器比较器优先
这里面Student类和TreeSet容器都具有比较性,Student是age主条件----age相同,比较name
容器本身是:name主条件----name相同,比较age
返回的排序结果就是容器比较性的排序。
2. TreeSet总结
1). TreeSet的特点
(1). 可以对元素进行排序
(2). TreeSet保证元素的唯一性依据
2). TreeSet的两种排序方式
(1). 让元素本身具有比较性
(2). 让容器自身具有比较性
(3). 元素的可存储性
[1]. 自定义的类,如果重写了hashCode和equals两个方法,可以存入HashSet容器
[2]. 自定义的类,如果实现了Comparable的compareTo()方法,可以存入TreeSet容器。
【总结】如果自定义的类既重写了hashCode和equals,又实现了compareTo,那么这个类的元素既可以存入HashSet容器,也可以存入TreeSet容器。