Java:TreeSet 的问题

标签 java generics treeset

我有一个 Odp 类。我想使用 TreeSet 来保存 Odp 对象的排序集合。但是,我一直遇到问题。

public class OdpStorage {

    private TreeSet<Odp> collection = new TreeSet<Odp>(); 

    public addOdp(Odp o) {
          return collection.add(o);
    }

    public int size() {
          return collection.size();
    }

}

collection.add(Odp o) 如果它已经在树中,应该什么也不做,对吗?不知何故,这个单元测试失败了:

OdpStorage ts = new OdpStorage();       
Odp ftw = new Odp("LOL");
    Odp ktr = new Odp("OMG");

    ts.addOdp(ftw);

    ts.addOdp(ftw); //should do nothing
    ts.addOdp(ftw); //should do nothing
    ts.addOdp(ftw); //should do nothing
    ts.addOdp(ktr);

assertEquals(2, ts.size());

断言失败。它期望 2,但返回值是 5。为什么? odp.equals() 函数会搞砸吗?

同样,调用 collection.contains(o) 也会失败,即使集合 X 中有一个对象 o.equals(X) 返回 true。

Odp的.equals()函数:(由Eclipse生成)

public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (!(obj instanceof Odp))
        return false;
    Gene other = (Odp) obj;
    if (sequence == null) {
        if (other.sequence != null)
            return false;
    } else if (!sequence.equals(other.sequence))
        return false;
    return true;
}

比较:

/**
 * this = g0
 * if they are equal, g1 is presumed to come first
 * 
 *  @return -1 if g0 comes before g1; 1 if g0 comes after g1
 */
@Override
public int compareTo(Odp g1) {

    if (sequence.length() < g1.getSeq().length()) {
        return -1;
    }
    else if (sequence.length() > g1.getSeq().length()) {
        return 1;
    }

    if (sequence.compareTo(g1.getSeq()) < 0) {
        return -1;
    }

    return 1;
}

hashCode() 未被覆盖。有问题吗?

更新 hashCode()如下:

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result
            + ((sequence == null) ? 0 : sequence.hashCode());
    return result;
}

但这仍然不能解决问题。

最佳答案

您的 compareTo 实现永远不会返回 0。当对象实例相等时,它应该返回 0。

关于Java:TreeSet 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1549524/

相关文章:

Java 执行 Ruby 脚本时收到错误;终端没有

java - 静态工厂方法不起作用

Java泛型为什么我不能实例化泛型类型

c# - 内置类型的通用 EventArgs

java - 自定义 TreeSet 打印 Map.Entry 值的方式

java - 允许重复的 TreeSet 或 TreeMap

tree - Java TreeSet 是如何实现的

java - 使用 JDBC 读取数据库

Java 泛型 - 编译器错误

java - 解析json的问题