我已经重写了下面给出的类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
在put
和get()
的情况下内部调用hashCode()
。在contains()
的情况下调用equals
。请澄清一下。
当您在HashMap
中put
某个东西时,hashCode()
方法是在键上调用的,而不是在值上调用的。因此,在这种情况下,在s1.getName()
和s2.getName()
上调用的是来自String
的hashCode
。
您使用的是java.lang.String值"name"作为键,因此不会调用对象上的hashcode方法。
如果你要做Map<供应商,对象>或其他什么,则会调用它。