我正在尝试以这种方式构建一个具有两个键的 HashMap:首先我创建了一个仅是数据结构的类。
public class Tarta {
public String nome;
public String data;
public Tarta(String nome, String data) {
this.nome = nome;
this.data = data;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}
然后我通过在另一个类中编写此内容来填充我的 map :
mappaTarta.put(new Tarta(nome, data), peso);
在编译期间我没有错误,但在测试时我得到了 null,例如:
System.out.println(lr.leggiRecord().get(new Tarta("R", "15/11/2015")));
你能解释一下为什么吗? 谢谢
最佳答案
如果您想使用项目作为 HashMap
中的键,则需要重写它们的 equals
和 hashCode
方法。否则,默认实现会将使用相同参数创建的两个实例视为不同的实例,因为它们是两个不同的实例。
目前:
Tarta a = new Tarta("foo", "bar");
Tarta b = new Tarta("foo", "bar");
System.out.println(a == b); // false
System.out.println(a.equals(b)); // false
System.out.println(a.hashCode() == b.hashCode()); // false
示例实现:
@Override public boolean equals(Object other) {
if (other == this) return true;
if (other instanceof Tarta) {
Tarta that = (Tarta) other;
return Objects.equals(this.name, that.name)
&& Objects.equals(this.data, that.data);
}
return false;
}
@Override public int hashCode() {
return Objects.hash(name, data);
}
然后:
Tarta a = new Tarta("foo", "bar");
Tarta b = new Tarta("foo", "bar");
System.out.println(a == b); // false - they are still different instances
System.out.println(a.equals(b)); // true
System.out.println(a.hashCode() == b.hashCode()); // true
请注意,建议仅使用不可变对象(immutable对象)作为 HashMap 中的键:至少应将 name
和 data
设置为 Final,并将类设置为 final
也使其真正不可变。
关于Java:具有两个键的 HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34226469/