代码如下
import java.util.TreeSet;
import java.util.Iterator;
class TreeSetDemo {
public static void main(String[] args)
{
Student a = new Student("lisi01",20);
Student b = new Student("lisi001",20);
Student c = new Student("lisi02",18);
Student d = new Student("lisi04",17);
Student e = new Student("lisi03",15);
TreeSet ts = new TreeSet();
ts.add(a);
ts.add(b);
ts.add(c);
ts.add(d);
ts.add(e);
Iterator it = ts.iterator();
while(it.hasNext())
{
Student xxx=(Student)it.next();
System.out.println(xxx.name+","+xxx.age);
}
}
}
class Student implements Comparable
{
public int compareTo(Object obj)
{
if(!(obj instanceof Student))
throw new RuntimeException("不是学生类");
Student ss = (Student)obj;System.out.println(this.name+",compareTo,"+ss.name);
if(ss.age>this.age)
return -1;
if(ss.age==this.age)
return this.name.compareTo(ss.name);//使用String自身的比较方法
return 1;
}
Student(String name,int age)
{
this.name=name;
this.age=age;
}
int age;
String name;
}
1.让元素自身具备比较性:
让比较对象的类实现Comparable接口,复写compareTo()方法
2.比较器方法,将比较器的对象作为参数传给构造函数:例如
TreeSet ts = new TreeSet( new MyComparator);
新定义一个类,实现Comparator接口,复写compare()方法。
当两种排序都存在时,以比较器为主。
第二种方法具体实现如下:
package note.heima;
import java.util.Comparator;
import java.util.TreeSet;
import java.util.Iterator;
class TreeSetDemo2 {
public static void main(String[] args)
{
Student2 a = new Student2("lisi01",20);
Student2 b = new Student2("lisi001",20);
Student2 c = new Student2("lisi02",18);
Student2 d = new Student2("lisi04",17);
Student2 e = new Student2("lisi03",15);
Student2 f = new Student2("lisi03",15);
TreeSet ts = new TreeSet(new MyComp());
ts.add(a);
ts.add(b);
ts.add(c);
ts.add(d);
ts.add(e);
ts.add(f);
Iterator it = ts.iterator();
while(it.hasNext())
{
Student2 xxx=(Student2)it.next();
System.out.println(xxx.name+","+xxx.age);
}
}
}
class MyComp implements Comparator
{
public int compare(Object o1,Object o2)
{
Student2 s1 = (Student2)o1;
Student2 s2 = (Student2)o2;
int num = s1.name.compareTo(s2.name);
if (num>0)
return 1;
if (num<0)
return -1;
if (num == 0)
{
return new Integer(s1.age).compareTo(new Integer(s2.age));
}
return num;
}
}
class Student2 implements Comparable
{
public int compareTo(Object obj)
{
if(!(obj instanceof Student2))
throw new RuntimeException("不是学生类");
Student2 ss = (Student2)obj;System.out.println(this.name+",compareTo,"+ss.name);
if(ss.age>this.age)
return -1;
if(ss.age==this.age)
return this.name.compareTo(ss.name);//使用String自身的比较方法
return 1;
}
Student2(String name,int age)
{
this.name=name;
this.age=age;
}
int age;
String name;
}