Mee*_*ary 1 java equals hashmap hashcode
我在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);
}
}
Run Code Online (Sandbox Code Playgroud)
此类的对象将添加到HashMap,其name字段为Key.
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"));
Run Code Online (Sandbox Code Playgroud)
但是,当我put()或get()一个元素我的被覆盖的hashCode()方法没有被调用.equals()我使用的情况也是如此contains(Key key).我认为HashMap内部调用hashCode()以及put和get().而equals被称为中的情况下contains().请注意这一点.
当你put在a中的某个东西时HashMap,该hashCode()方法是在键上调用的,而不是在值上调用的.所以在这种情况下,它是hashCode由String被调用的s1.getName()和s2.getName().