HashSet 中的 一点疑惑

weixin_35722556 2016-08-03 04:20:49
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!
*/
...全文
92 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

62,628

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧