3

I've created a java dictionary using java.util.Hashtable with 2-tuple of strings as it's keys and int as values.

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

I used to above class to initialize a dictionary:

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

Now I'm unable to check whether a key exists in dict, I mean I am unable to pass pair of strings as argument to dict.containsKey() method.

lavee_singh
  • 1,379
  • 1
  • 13
  • 21

2 Answers2

2

You need to implement hashCode and equals for stuff you want to use as Hashtable keys. If you don't do that, the default mechanism is used, and that will use object identity, not object equality (meaning two tuples are not considered equal even if they contain "equal" entries).

And the key fields should really be immutable, otherwise it can also break things.

Thilo
  • 257,207
  • 101
  • 511
  • 656
1

Try something like this:

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;
    }
}

I've assumed that e and f is not null. If it can be null then you must check whether e == null before the if(e.equals(other.getE()) to prevent a NPE.

Further notes:

M. Shaw
  • 1,742
  • 11
  • 15