【问题标题】:Check whether a tuple key exists in dictionary in javajava 检查字典中是否存在元组键
【发布时间】:2015-11-26 06:45:12
【问题描述】:

我使用 java.util.Hashtable 创建了一个 java 字典,其中 2 元组字符串作为键,int 作为值。

class pair<e,f>{
  public e one;
  public f two;
}

我以前用上面的类来初始化一个字典:

Dictionary<pair<String, String>, Integer> dict = new Hashtable();

现在我无法检查 dict 中是否存在键,我的意思是我无法将一对字符串作为参数传递给 dict.containsKey() 方法。

【问题讨论】:

  • 类名以大写字母开头,例如 Pair。
  • 我认为这不重要!我的意思是为了功能。
  • 是的,功能无关紧要,重要的是代码的理解和可维护性。
  • 我知道,但这里的功能才是最重要的。顺便谢谢。

标签: java dictionary tuples


【解决方案1】:

您需要为要用作 Hashtable 键的内容实现 hashCodeequals。如果您不这样做,则使用默认机制,这将使用对象标识,而不是对象相等(这意味着即使两个元组包含“相等”条目,它们也不被视为相等)。

而且关键字段确实应该是不可变的,否则也会破坏。

【讨论】:

【解决方案2】:

试试这样的:

public class Pair<E, F> {
    private final E e;
    private final F f;
    public Pair(E e, F f) {
        this.e = e;
        this.f = f;
    }

    public E getE() {
        return e;
    }
    public F getF() {
        return f;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Pair<E,F> other = (Pair<E,F>) obj;
        if (!this.e.equals(other.getE())) {
           return false;
        }
        if (!this.f.equals(other.getF())) {
            return false;
        }
        return true;
    }

    @Override
    public int hashCode() {
        hash = 53 * e.hashCode() + f.hashCode();
        return hash;
    }
}

我假设ef 不是null。如果可以是null,则必须检查e == null是否在if(e.equals(other.getE())之前,以防止NPE。

补充说明:

【讨论】:

    猜你喜欢
    • 2017-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-25
    • 2012-03-27
    • 2010-12-08
    • 2012-06-15
    相关资源
    最近更新 更多