本文转自:http://hi.baidu.com/jiangyangw3r/item/c26e780bcbf2f5354bc4a348
示例1:
package com.xy6;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class EqualDemo {
public static void main(String[] args){
String s1=new String("zhaoxudong");
String s2=new String("zhaoxudong");
System.out.println(s1==s2);//false
System.out.println(s1.equals(s2));//true
System.out.println(s1.hashCode());//s1.hashcode()等于s2.hashcode()
System.out.println(s2.hashCode());
Set<String> hashset=new HashSet<String>();
hashset.add(s1);
hashset.add(s2);
Iterator it=hashset.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
输出:
false
true
-967303459
-967303459
zhaoxudong
package com.xy6;
import java.util.HashSet;
import java.util.Iterator;
public class EqualDemo2 {
public static void main(String[] args){
HashSet<Student> hs = new HashSet<Student>();
hs.add(new Student(1, "zhangsan"));
hs.add(new Student(2, "lisi"));
hs.add(new Student(3, "wangwu"));
hs.add(new Student(1, "zhangsan"));
Iterator it = hs.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
class Student {
int num;
String name;
Student(int num, String name) {
this.num = num;
this.name = name;
}
public String toString() {
return num + ":" + name;
}
// 将hashCode equals注释,程序将输出四个数据
public int hashCode() {
return num * name.hashCode();
}
public boolean equals(Object o) {
Student s = (Student) o;
return num == s.num && name.equals(s.name);
}
}
输出:
1:zhangsan
3:wangwu
2:lisi
本文通过两个示例深入探讨了Java中equals方法与hashCode方法的实现原理及其在集合类如HashSet中的应用。示例展示了如何自定义类来正确覆盖这两个方法以确保对象的正确比较与存储。
2474

被折叠的 条评论
为什么被折叠?



