想有一个自定义对象,先搞一个Student类。
//Student.java
package com.huowolf;
public class Student implements Comparable{
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
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;
}
public int compareTo(Object obj) {
if(!(obj instanceof Student))
throw new RuntimeException("不是学生对象");
Student stu=(Student)obj;
if(this.age>stu.age)
return 1;
if(this.age==stu.age)
return this.name.compareTo(stu.name);
return -1;
}
}
//TreeSetDemo1.java
package com.huowolf;
import java.util.Iterator;
import java.util.TreeSet;
/**
* @author huowolf
*排序的第一种方式:让元素自身具备比较性。
*元素需要实现Comparable接口,覆盖compareTo方法
*这种方式也元素的自然顺序
*/
public class TreeSetDemo {
public static void main(String[] args) {
TreeSet<Object> ts= new TreeSet<Object>();
ts.add(new Student("lisi01",22));
ts.add(new Student("lisi02",20));
ts.add(new Student("lisi03",18));
ts.add(new Student("lisi04",25));
ts.add(new Student("lisi05",18));
Iterator it = ts.iterator();
while(it.hasNext()) {
Student stu = (Student) it.next();
System.out.println("姓名:"+stu.getName()+" 年龄:"+stu.getAge());
}
}
}
//TreeSetDemo2.java
package com.huowolf;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
/**
* @author huowolf
*排序的第二种方式:当元素自身不具备比较性时,让集合自身具备比较性。
*在集合初始化时,指定比较器。
*/
public class TreeSetDemo2 {
public static void main(String[] args) {
TreeSet<Object> ts= new TreeSet<Object>(new MyCompare());
ts.add(new Student("lisi01",22));
ts.add(new Student("lisi02",20));
ts.add(new Student("lisi03",18));
ts.add(new Student("lisi04",25));
ts.add(new Student("lisi02",27));
Iterator it = ts.iterator();
while(it.hasNext()) {
Student stu = (Student) it.next();
System.out.println("姓名:"+stu.getName()+" 年龄:"+stu.getAge());
}
}
}
class MyCompare implements Comparator {
public int compare(Object o1,Object o2) {
Student s1 = (Student) o1;
Student s2 = (Student) o2;
int num = s1.getName().compareTo(s2.getName());
if(num==0)
//return s1.getAge()-(s2.getAge());
return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
return num;
}
}