仅使用一个属性作为键制作自定义 class 地图

Make Custom class map with only one attribute as key

我有一个class如下-

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

我想创建一张地图 class -

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

但我希望仅根据头部而不是头部和尾部来搜索密钥。我应该如何实现这个功能? 我需要这个,这样可以避免头部相同但尾部不同的头部,尾部对值。

您可以创建一些关键逻辑以保存在地图上


public class Snake {
    private int head;
    private int tail;

    // create any key logic
    public String getKey(){
       return head + "-" + tail; // eg. with both but can be any other one
    }

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

使用具有关键逻辑的地图

Map<String,Snake> map = new HashMap<>();
map.put(snake.getKey(), snake );

HashMap and HashSet use the Java senses of equals and hashCode。如果您在 Snake 实现中覆盖 Object 的那些方法,使它们仅基于 head 的值,那么 Snake 实例将表现为等效的 Map 键(或 Set 成员)只要它们具有相同的 head 值。

请注意,这可能是令人困惑的行为:您告诉 Java 这些对象在所有意义上都应该被视为相等,而不管 tail 的值如何!如果 tail 是固定的并且可以根据 head 或其他一些值计算,这可能是个好主意,但如果 tail 可以在 Snake 之间合理变化,这可能是一个非常糟糕的主意] 具有相同 head 的实例。您可能会选择使用显式键,正如 Dilermando Lima 在他的回答中所建议的那样,或者如果平等感对于特定的集合或地图来说是独一无二的,您可以尝试像 Guava 的 Equivalence 这样的实用程序,它允许您包装您的具有自定义 equalshashCode.

的对象