【发布时间】:2012-05-22 12:42:36
【问题描述】:
对不起......关于这个愚蠢/愚蠢的问题,伙计们:
为什么不应用equals() 和hashCode()?
目前,他们只能按照我对HashSet 的预期工作。
更新
EVEN 键值 5 重复但不调用 equals 和 hashCode。
我也想在 Value 上应用它。
就像这个例子中HashSet调用equal和hashCode一样,为什么hashMap即使for key也不被调用equals和hashCode。
UPDATE2 - 答案
HashMap 的 key(class->HashCode, equals) 将被调用。 谢谢你们。 我对此有点困惑。 :)
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 中,键是散列的,而不是值
-
hashMap 如何调用 hascode & equals
-
Map 调用 equals 和 hashCode 方法,它正在这样做——对于 Integer 键!如果您希望 Map 检查 Employee hashCode 和/或等于,则 Employee 必须是 Key 而不是 Value。
-
为什么即使 for key 重复也没有调用 hashMap(equals & hascode)。
-
很高兴你已经弄明白了! 1+