user2652995
user2652995

Reputation: 57

Hashmap 1 key 2 values - using containsvalue

Somewhere in stackoverflow i found solution about 2 values.

public class Pair<A, B> {
    A first = null;
    B second = null;

    Pair(A first, B second) {
        this.first = first;
        this.second = second;
    }

    public A getFirst() {
        return first;
    }

    public void setFirst(A first) {
        this.first = first;
    }

    public B getSecond() {
        return second;
    }

    public void setSecond(B second) {
        this.second = second;
    }

}

public static HashMap<Player, Pair<HorseModifier, LivingEntity>> P_and_h = 
      new HashMap<Player,Pair<HorseModifier, LivingEntity>>();;

And the question:

P_and_h.put(p, new Pair(hm, hm.getHorse()));

if(P_and_h.containsValue(HorseModifier))` - dont working ( this is first object)

Upvotes: 1

Views: 641

Answers (4)

Grim
Grim

Reputation: 1974

Too bad, this is not possible!

By instict i would say Pair needs to implement equals() but containsKey dont check by using equals(), it checks for identity using ==.

Too bad, you cant use HashMap.

  • Implement HashMap and override containsKey and containsValue.
  • Or may even better, create your own Map.

Upvotes: 0

arjacsoh
arjacsoh

Reputation: 9232

Since the value is of type Pair you should search for a Pair and pass it as parameter in the method containsValue(); You should also override hasCode() and equals() if you want to find the "meaningfully" equal objects, namely the objects which contain the same fields, in your case the same HorseModifier and LivingEntity. Else it checks only if the reference you pass refers to an Object which exists in Map, irrespective of its fields.

Upvotes: 0

Ravi K Thapliyal
Ravi K Thapliyal

Reputation: 51711

You should be using Map#containsKey()

if (P_and_h.containsKey(p)) {
  // ...
}

or, pass the same Pair

if (P_and_h.containsValue(new Pair(hm, hm.getHorse()))) {
  // ...
}

Using containsValue() is not recommended. Since, it can't leverage the hashing (which is done for keys not their values) it would give you a terrible performance. More info at Map#containsValue()

This operation will probably require time linear in the map size for most implementations of the Map interface.

Upvotes: 0

Prabhaker A
Prabhaker A

Reputation: 8473

you should check with Pair object like this P_and_h.containsValue(pair).

containsValue() Returns true if this map maps one or more keys to the specified value.

Upvotes: 1

Related Questions