62,628
社区成员
发帖
与我相关
我的任务
分享import java.util.*;
class A
{
//Override object's equals & hashCode 方法
public boolean equals(Object obj){
System.out.println(this.getClass().getName() +"hashSet 创建时 equals 调用");
return true;
}
}
class B
{
public int hashCode(){
System.out.println(this.getClass().getName() + "hashSet 创建时 hashCode 调用");
return 1;
}
}
class C
{
public boolean equals(Object obj){
System.out.println(this.getClass().getName() +"hashSet 创建时 equals 调用");
return true;
}
public int hashCode(){
System.out.println(this.getClass().getName() + "hashSet 创建时 hashCode 调用");
return 2;
}
}
class SetDemo
{
public static void main(String[] args)
{
HashSet books = new HashSet();
books.add(new A());
books.add(new A());//hashCode 不一样就步调用equals 方法
books.add(null);
//System.out.println(books.add(null)); 只能有一个null 引用
books.add(new B());
books.add(new B());
books.add(new C());
books.add(new C());
System.out.println(books.size());
System.out.println(books);
System.out.println("Create over!");
}
}
/*
Output Result :
BhashSet 创建时 hashCode 调用
BhashSet 创建时 hashCode 调用 //为什么有两个B@1?
ChashSet 创建时 hashCode 调用
ChashSet 创建时 hashCode 调用
ChashSet 创建时 equals 调用
6
BhashSet 创建时 hashCode 调用
BhashSet 创建时 hashCode 调用
ChashSet 创建时 hashCode 调用
[null, B@1, B@1, C@2, A@121a2cc7, A@37bbea67]
Create over!
*/