Search code examples
javaoophashmap

Make Custom class map with only one attribute as key


I have a class as follows -

public class Snake {
    private int head;
    private int tail;
    public Snake(int head, int tail) {
        super();
        this.head = head;
        this.tail = tail;
    }
}

I want to create a map of this class -

Map<Snake,Integer> map = new HashMap<>();

But I want the key to be searched only on the basis of the head not both the head and tail. How should I implement this functionality? I need this so that head, tail pair values where head is the same but tails are different can be avoided.


Solution

  • HashMap and HashSet use the Java senses of equals and hashCode. If you override those methods of Object in your Snake implementation such that they are based only on the value of head, then Snake instances will behave as equivalent Map keys (or Set members) as long as they have the same head value.

    Note that this might be confusing behavior: You are telling Java that those objects should be considered equal in all senses regardless of the value of tail! This might be a good idea if tail is fixed and calculable based on head or some other value, but it might be a very bad idea if tail can reasonably vary between Snake instances that have the same head. You might instead choose to use an explicit key as Dilermando Lima suggests in his answer, or if the sense of equality is unique to the particular set or map, you might try a utility like Guava's Equivalence that allows you to wrap your objects with a custom equals and hashCode.