当TreeSet中两种排序方式都存在时以比较器为主,可是运行的结果却不是这样。
```import java.util.*;
public class TreeSetDemo {
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void main(String[] args)
{
TreeSet ts = new TreeSet();
ts.add(new Student("lisi02",22));
ts.add(new Student("lisi007",20));
ts.add(new Student("lisi08",50));
ts.add(new Student("lisi06",40));
ts.add(new Student("lisi07",40));
Iterator it = ts.iterator();
while(it.hasNext())
{
Student stu = (Student)it.next();
System.out.println(stu.getName()+"..."+stu.getAge());
}
}
}
@SuppressWarnings("rawtypes")
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)
{
//return 1;
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);
}
else
return -1;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
@SuppressWarnings("rawtypes")
class Mycomparet 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 num;
}
}
结果
、lisi02........compareto...lisi02
lisi007........compareto...lisi02
lisi08........compareto...lisi02
lisi06........compareto...lisi02
lisi06........compareto...lisi08
lisi07........compareto...lisi02
lisi07........compareto...lisi08
lisi07........compareto...lisi06
lisi007...20
lisi02...22
lisi06...40
lisi07...40
lisi08...50