简体   繁体   中英

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)

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.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM