如下面的代码:public class Member implements Comparable<Member> {
private String name;
private int age;
private int grade; 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 getGrade() {
return grade;
} public void setGrade(int score) {
this.grade = score;
} @Override
public String toString() {
return this.name + "(" + this.age + ")" + ":" + this.grade;
} @Override
public int compareTo(Member o) {
if (this.name.equals(o.getName()) && this.age == o.age) {
return 0;
}
// 升序 当前元素 - 传入元素 值
// 成绩升序
int result1 = this.getGrade() - o.getGrade();
if (result1 == 0) {
// 姓名升序
int result2 = this.name.compareTo(o.name);
if (result2 == 0) {
// 年龄升序
int result3 = this.age - o.age;
return result3;
} else {
return result2;
}
} else {
return result1;
}
}
}现有数据:Jack1(18):70
Appl2(20):70
Appl2(20):70
Appl2(20):72
Adpl2(20):73
ccpl2(20):75
bppl2(20):75
当我将这组数据加入TreeSet的时候,返回的数据是:Appl2(20):70
Jack1(18):70
Appl2(20):72
Adpl2(20):73
bppl2(20):75
ccpl2(20):75
可以看到Appl2还有一个并没有排除,这是为啥呢???

解决方案 »

  1.   

    不是很理解你要实现的目的呢。。
    从代码逻辑上看,应该是:
    当两个人姓名、年龄完全一致时,值相等。
    测试数据的格式是
    姓名(年龄):成绩
    那App12(20)都应该是相等的。
    然而再往下看,姓名、年龄不同时,比较的优先顺序却是
    分数,姓名,年龄。
    这样就完全违背了Compare规范啊。
      

  2.   

    我觉着需要好好思考一下, 把equals和compareTo分开。
    顺便我不是很清楚为什么会用姓名和年龄来判断两个人是否是同一个人
      

  3.   

    Treeset 是用Treemap来实现的,查看一下TreeMap的put方法的代码,或许对你有帮助:
    你的Member是实现了Comparable接口,照此关注下面部分代码:Comparable<? super K> k = (Comparable<? super K>) key;
    do {
        parent = t;
        cmp = k.compareTo(t.key);
        if (cmp < 0)
            t = t.left;
        else if (cmp > 0)
            t = t.right;
        else
            return t.setValue(value);
    } while (t != null);
    可以看到,只要grade不相等,他就会认为是不同的对象,所以会有两个App12(20)的存在。