TreeSet可以对Set集合中的元素进行排序,通过以下两种方式讲解TreeSet排序的方法;
方法一:让元素自身具备比较性,元素需要实现Compareable接口,覆盖CompareTo方法,这种方法称为元素的自然排序
或者默认排序
/**
* 需求:往TreeSet集合中存储自定义的学生对象,想按照学生的年龄进行排序,
* 年龄相同的在比较学生姓名,如果姓名和年龄都相同就是同一个人,就不能存入TreeSet集合中。
*
* */
public class TreeSetDemo {
public static void main(String[] args) {
TreeSet ts = new TreeSet();
ts.add(new Student("lisi02",20));
ts.add(new Student("lisi004",23));
ts.add(new Student("lisi08",21));
ts.add(new Student("lisi09",21));
Iterator it = ts.iterator();
while(it.hasNext()){
Student s = (Student)it.next();
System.out.println(s.getName()+"...."+s.getAge());
}
}
}
class Student implements Comparable{//该接口强制让学生具备比较性
private String name;
private int age;
Student(String name,int age){
this.name = name;
this.age = age;
}
public int compareTo(Object obj){
if(!(obj instanceof Student)){
throw new RuntimeException("不是学生对象");
}
Student s = (Student)obj;
//System.out.println(this.name+"....compareto...."+s.name);
if(this.age>s.age)
return 1;
if(this.age==s.age)//注意:排序时,当主要条件相同时,一定要判断一下次要条件
{
return this.name.compareTo(s.name);
}
return -1;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
方法二:当元素自身不具备比较性或者具备的比较性不是所需要的,这时,就需要让容器自身具备比较性;在集合初始化时,就具有比较方式。
/*
* 当元素自身不具备比较性,或者具备的比较性不是所需要的,这是需要让容器自身具备比较性
* 定义一个比较器,将比较器对象作为参数传递给TreeSet集合的构造函数(定义一个类,实现Comparator接口,覆盖compare方法)
*
* 按照学生姓名排序
*
* 当两种排序都存在时,以比较器为主。
* */
public class TreeSetDemo2 {
public static void main(String[] args) {
TreeSet ts = new TreeSet(new MyCompare());
ts.add(new Student1("lisi02",20));
ts.add(new Student1("lisi004",23));
ts.add(new Student1("lisi08",26));
ts.add(new Student1("lisi0019",21));
ts.add(new Student1("lisi0019",19));
ts.add(new Student1("lisi08",26));
Iterator it = ts.iterator();
while(it.hasNext()){
Student1 s = (Student1)it.next();
System.out.println(s.getName()+"...."+s.getAge());
}
}
}
//定义一个比较器
class MyCompare implements Comparator{
public int compare(Object o1, Object o2) {
Student1 s1= (Student1)o1;
Student1 s2= (Student1)o2;
int num = s1.getName().compareTo(s2.getName());
if(num==0){
if(s1.getAge()>s2.getAge())
return 1;
if(s1.getAge()==s2.getAge())
return 0;
return -1;
}
return num;
}
}
class Student1 implements Comparable{//该接口强制让学生具备比较性
private String name;
private int age;
Student1(String name,int age){
this.name = name;
this.age = age;
}
public int compareTo(Object obj){
if(!(obj instanceof Student1)){
throw new RuntimeException("不是学生对象");
}
Student1 s = (Student1)obj;
//System.out.println(this.name+"....compareto...."+s.getName());
if(this.age>s.getAge())
return 1;
if(this.age==s.getAge())//注意:排序时,当主要条件相同时,一定要判断一下次要条件
{
return this.name.compareTo(s.getName());
}
return -1;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}