- 论坛徽章:
- 0
|
- import java.util.*;
- class Student{
- public String name;
- public int id;
-
-
-
- public Student(String name, int id) {
- super();
- this.name = name;
- this.id = id;
- }
- public String toString()
- {
- return "id:" + id + " name:" + name;
- }
-
- public int hasCode()
- {
- return name.hashCode()^id;
- }
-
- public boolean equals(Object obj)
- {
- if(obj instanceof Student)
- {
- Student s = (Student)obj;
- if(s.id == this.id && s.name.equals(this.name))
- return true;
- }
- return false;
- }
-
- }
- public class Test{
- public static void main(String[] args)
- {
- int count = 0;
- HashSet<Student> h = new HashSet<Student>();
- Student s1 = new Student("sb3",1002);
- Student s2 = new Student("sb2",1001);
- Student s3 = new Student("sb3",1002);
- System.out.println(s1.hasCode());
- System.out.println(s3.hasCode());
- System.out.println(s1.equals(s3));
- h.add(s1);
- h.add(s3);
- h.add(s2);
- Iterator<Student> it = h.iterator();
- while(it.hasNext()){
- System.out.println("num"+ count + ":" );
- System.out.println(it.next());
- count++;
- }
- }
- }
复制代码 上面是我的代码
- 运行结果:
- 112686
- 112686
- true
- num0:
- id:1002 name:sb3
- num1:
- id:1002 name:sb3
- num2:
- id:1001 name:sb2
复制代码 我想问HashSet 是怎么判断两个加入的对象是否和已经存在的对象相同呢?难道不是通过对象本身的equals和hashcode 吗 ?
这里s1和s3的hashcode相同 且equals返回true怎么还能加入到HashSet中呢?求大侠解答 非常感谢
|
|