【发布时间】:2014-10-15 19:46:33
【问题描述】:
我在下面给出的类Supplier 中覆盖了hashCode() 和equals() 方法。
public class Supplier {
private final String name;
public Supplier(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public int hashCode() {
char[] charArray = name.toCharArray();
int sumOfchars = 0;
for (char element : charArray) {
sumOfchars += element;
}
return 51 * sumOfchars;
}
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (getClass() != o.getClass()) {
return false;
}
final Supplier other = (Supplier) o;
return this.name.equals(other.name);
}
}
这个类的对象被添加到一个以name字段为Key的HashMap中。
Supplier s1 = new Supplier("supplierA");
Supplier s2 = new Supplier("supplierB");
Map<String, Supplier> supplierMap = new HashMap<>();
supplierMap.put(s1.getName(), s1);
supplierMap.put(s2.getName(), s2);
supplierMap.containsKey("supplierA"));
但是,当我 put() 或 get() 一个元素时,我覆盖的 hashCode() 方法不会被调用。当我使用contains(Key key) 时,equals() 的情况也是如此。我认为HashMap 内部调用hashCode() 以防put 和get()。在contains() 的情况下调用equals。请对此有所了解。
【问题讨论】:
标签: java hashmap equals hashcode