Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TreeMap 采坑记 #21

Open
DraperHXY opened this issue Jan 21, 2019 · 0 comments
Open

TreeMap 采坑记 #21

DraperHXY opened this issue Jan 21, 2019 · 0 comments

Comments

@DraperHXY
Copy link
Owner

当我实现一个 TreeMap

TreeMap<Student<int age>,String name>

理所当然的认为 TreeMap 的 key,也就是 Student 类需要重写 equal 和 hashCode 方法,来确保键的唯一性

但实际上

treeMap.put(student1, "小米12");
treeMap.put(student2, "小米11");
treeMap.put(student3, "小米45");
treeMap.put(student4, "小米82");
treeMap.put(student5, "小米66");

连续 put 五次后得到的 Size 居然为 3

在 debug 过程中,跟随断点查看
在确定唯一性的时候并没有进入 equal 和 hashCode 方法
反而是在 TreeMap 中迟迟停留

而里面有一步

parent = t;
cmp = cpr.compare(key, t.key);
if (cmp < 0)
    t = t.left;
else if (cmp > 0)
    t = t.right;
else
    return t.setValue(value);

这让我想起了我的 compare 方法,好像找到问题了

@Override
public int compareTo(Student o) {
    if (this == o) {
        return 0;
    } else {
        if (this.age < o.getAge()) {
            return 0;
        } else {
            return 1;
        }
    }
}

我的比较方法没有返回负值得可能,这就意味着我的 t 对象(指针) 一指再往右边找,直到直接执行下面 else 的内容进行赋值

所以我的 treeMap 中的 Entry 总是被覆盖

所以修改 compare 方法,增加往左搜索的可能解决问题

int num = this.age - o.getAge();
//为0时候,两者相同:
if (num == 0) {
    return 0;
    //大于0时,传入的参数小:
} else if (num > 0) {
    return 1;
    //小于0时,传入的参数大:
} else {
    return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant