有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么hashmap对整数值求和

我正在从一个互联网示例中学习HashMap,我不明白为什么put()对整数值求和而不是替换它们?我试过使用字符串,但它确实替换了字符串,这是应该的

Javadoc说:

Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.

然而:

public class testMap {

    public static void main(String[] args) {

        HashMap<Dog, Integer> myH = new HashMap<>();
        Dog d1 = new Dog("white");
        Dog d2 = new Dog("green");
        Dog d3 = new Dog("purple");
        Dog d4 = new Dog("white");
        Dog d5 = new Dog("green");
        Dog d6 = new Dog("white");
        Dog d7 = new Dog("white");

        myH.put(d1, 10);
        myH.put(d2, 20);
        myH.put(d3, 30);
        myH.put(d4, 14);
        myH.put(d5, 15);
        myH.put(d6, 60);
        myH.put(d7, 10);

        System.out.println(myH.size());

        for (Entry<Dog,Integer> line : myH.entrySet() ) {
            System.out.println(line.getKey().toString()+" - "+line.getValue());
        }
    }

}

class Dog {
    String color;

    Dog(String c){
        color = c;
    }
    @Override
    public String toString() {
        return color + " dog" ;

    }
    @Override
    public boolean equals(Object o) {
        return ((Dog) o).color == this.color;

    }
    @Override
    public int hashCode() {
        return color.length();
    }

}

我收回这个问题。正如javadoc所说,它工作得非常完美,我只是没有对结果给予足够的关注。此外,帖子可以被删除,因为它不会询问任何有价值的信息


共 (1) 个答案

  1. # 1 楼答案

    对于字符串相等性检查,请始终使用equals()Btw在这种情况下==是可以的

    @Override
    public boolean equals(Object o) {
        return ((Dog) o).color.equals(this.color);
    
    }
    

    顺便说一句,正在放映

    3
    green dog - 15
    white dog - 10
    purple dog - 30