Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将对象作为键添加到hashmap,该键仅等于实现的方法_Java_Hashmap - Fatal编程技术网

Java 将对象作为键添加到hashmap,该键仅等于实现的方法

Java 将对象作为键添加到hashmap,该键仅等于实现的方法,java,hashmap,Java,Hashmap,我有一个下面的类,它只覆盖了equals class S { String txt = null; S(String i) { txt = i; } public boolean equals(Object o) { S cc = (S) o; if (this.txt.equals(cc.txt)) { return true; } else {

我有一个下面的类,它只覆盖了equals

class S {

    String txt = null;

    S(String i) {
        txt = i;
    }       

    public boolean equals(Object o) {
        S cc = (S) o;
        if (this.txt.equals(cc.txt)) {
            return true;
        } else {
            return false;
        }
    }

    //Default hash code will be called
    /*public int hashCode(){
        return txt.hashCode();
    }*/

}
我将此类对象添加到哈希映射中,如下所示

    public static void main(String args[]) {
            S s1 = new S("a");
            S s2 = new S("b");
            S s3 = new S("a");

            Map m = new HashMap();
            m.put(s1, "v11");
            m.put(s2, "v22");
            m.put(s3, "v33");

            System.out.println(m.size());
            System.out.println(m.get(s1));
    }

可以解释打印结果3和v11吗?s1的值v11不应该被v33替换吗?因为相同的equals键作为s3放置?

您还必须重写
hashCode
。如果
a.equals(b)
a.hashCode()
必须等于
b.hashCode()
hashCode
的实现决定了条目将存储在哪个bucket中。如果不重写
hashCode
,可能会在两个不同的存储桶中存储两个相等的键

将此添加到您的
S
类:

@Override
public int hashCode() {
    if (txt == null)
        return 0;
    return txt.hashCode();
}

您还必须重写hashCode。如果
a.equals(b)
a.hashCode()
必须等于
b.hashCode()
hashCode
的实现决定了条目将存储在哪个bucket中。如果不重写
hashCode
,可能会在两个不同的存储桶中存储两个相等的键

将此添加到您的
S
类:

@Override
public int hashCode() {
    if (txt == null)
        return 0;
    return txt.hashCode();
}

你所描述的情况违反了合同。如果您以违反
hashCode()合同的方式覆盖
equals()
您也必须覆盖
hashCode()

您描述的情况违反了合同。如果您重写
equals()
的方式违反了
hashCode()的约定,
您也必须重写
hashCode()

只有当两个对象具有相同的哈希代码(=它们将位于同一个“bucket”)时才会调用
#equals
。您是否尝试过阅读有关
HashMap
行为的内容?例如:
#equals
仅在两个对象具有相同的哈希代码(=它们将位于相同的“bucket”中)时才会被调用。您是否尝试过阅读有关
HashMap
行为的内容?例如: