guaishushus 2017-10-25 13:00 采纳率: 0%
浏览 861

java集合TreeSet中排序问题

当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


  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 #MATLAB仿真#车辆换道路径规划
    • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
    • ¥15 数据可视化Python
    • ¥15 要给毕业设计添加扫码登录的功能!!有偿
    • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
    • ¥15 微信公众号自制会员卡没有收款渠道啊
    • ¥100 Jenkins自动化部署—悬赏100元
    • ¥15 关于#python#的问题:求帮写python代码
    • ¥20 MATLAB画图图形出现上下震荡的线条
    • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘