Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether a tuple key exists in dictionary in java

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.

like image 889
lavee_singh Avatar asked Aug 19 '26 03:08

lavee_singh


2 Answers

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.

like image 129
Thilo Avatar answered Aug 21 '26 17:08

Thilo


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:

  • You should in almost all cases set members of a class to private (except static members).

  • Proper Java convention is to have class names in CapitalizedWords.

  • Generic type parameters should be a single upper-case character.

like image 20
M. Shaw Avatar answered Aug 21 '26 16:08

M. Shaw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!