對不起......這個愚蠢/愚蠢的問題,夥計們:的HashMap與覆蓋equals和hashCode不工作
爲什麼沒有被應用equals()
和hashCode()
?
目前它們只能按照我對HashSet
的預期工作。
UPDATE
即使鍵值5重複,但是它不調用equals和hashCode。
我想將其應用於Value。
就像這個例子中HashSet調用equal和hashCode一樣,爲什麼hashMap沒有被調用equals和hashCode,即使是key。
UPDATE2 - ANSWER
HashMap中的鍵(類 - >的hashCode,等於)將被調用。 謝謝大家。 我對此有點困惑。 :)
public class Employee {
int id;
String name;
int phone;
public Employee(int id, String name, int phone) {
this.id = id;
this.name = name;
this.phone = phone;
}
// Getter Setter
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Employee other = (Employee) obj;
System.out.println("Employee - equals" + other.getPhone());
if (this.id != other.id) {
return false;
}
if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {
return false;
}
if (this.phone != other.phone) {
return false;
}
return true;
}
@Override
public int hashCode() {
System.out.println("Employee - hashCode");
int hash = 3;
hash = 67 * hash + this.id;
hash = 67 * hash + (this.name != null ? this.name.hashCode() : 0);
hash = 67 * hash + this.phone;
return hash;
}
}
____________________________________________________________________________________
public class MapClass {
public static void main(String[] args) {
Map<Integer,Employee> map = new HashMap<Integer,Employee>();
map.put(1, new Employee(1, "emp", 981));
map.put(2, new Employee(2, "emp2", 982));
map.put(3, new Employee(3, "emp3", 983));
map.put(4, new Employee(4, "emp4", 984));
map.put(5, new Employee(4, "emp4", 984));
**//UPDATE**
map.put(5, new Employee(4, "emp4", 984));
System.out.println("Finish Map" + map.size());
Set<Employee> set = new HashSet<Employee>();
set.add(new Employee(1, "emp", 981));
set.add(new Employee(2, "emp2", 982));
set.add(new Employee(2, "emp2", 982));
set.add(new Employee(3, "emp3", 983));
set.add(new Employee(4, "emp4", 984));
set.add(new Employee(4, "emp4", 984));
System.out.println(set.size());
}
}
輸出爲
Finish Map5
Employee - hashCode
Employee - hashCode
Employee - hashCode
Employee - equals982
Employee - equals982
Employee - hashCode
Employee - hashCode
Employee - hashCode
Employee - equals984
Employee - equals984
4
究竟是什麼問題?請記住,在HashMap中,密鑰被哈希,而不是值 –
我將如何調用哈希映射的hascode&equals –
Map調用equals和hashCode方法,並且這樣做 - 對於整數鍵!如果您希望Map檢查Employee hashCode和/或equals,那麼Employee必須是Key而不是Value。 –