Java 集合学习一 HashSet

[size=x-large][color=green][b]寒假在家,看书解闷。以下代码来自于疯狂Java讲义[/b][/color][/size]
[size=large][color=green]import java.util.*;

//类A的equals方法总是返回true,但没有重写其hashCode()方法
class A
{
public boolean equals(Object obj)
{
return true;
}
}
//类B的hashCode()方法总是返回1,但没有重写其equals()方法
class B
{
public int hashCode()
{
return 1;
}
}
//类C的hashCode()方法总是返回2,但没有重写其equals()方法
class C
{
public int hashCode()
{
return 2;
}
public boolean equals(Object obj)
{
return true;
}
}
public class TestHashSet
{
public static void main(String[] args)
{
HashSet books = new HashSet();
//分别向books集合中添加2个A对象,2个B对象,2个C对象
books.add(new A());
books.add(new A());
books.add(new B());
books.add(new B());
books.add(new C());
books.add(new C());
System.out.println(books);
}
}
//输出结果:[lee.B@1, lee.B@1, lee.C@2, lee.A@1fb8ee3, lee.A@c17164]
// PS :程序说明了两个HashSet集合判断元素相等的标准是hashcode和equals方法缺一不可[/color][/size]

[b][size=x-large][color=green]下面的程序从方面进行了验证[/b]

import java.util.*;
class R{
int count;
public R(int count){
this.count = count;
}
public String toString(){
return "R(count属性:" + count + ")";
}
public boolean equals(Object obj){
if (obj instanceof R){
R r = (R)obj;
if (r.count == this.count){
return true;
}
}
return false;
}
public int hashCode(){
return this.count;
}
}
public class TestHashSet2{
public static void main(String[] args) {
HashSet hs = new HashSet();
hs.add(new R(5));
hs.add(new R(-3));
hs.add(new R(9));
hs.add(new R(-2));
System.out.println(hs); //打印集合
//输出结果:[R(count属性:5), R(count属性:9), R(count属性:-3), R(count属性:-2)]
Iterator it = hs.iterator(); //获取集合的迭代器
R first = (R)it.next(); //取出第一个元素
first.count = -3; //为第一个元素的count属性赋值
//PS :注意这里仅仅是修改了count的属性值,并没有改了原有R对象的hascode
System.out.println(hs);//打印结合
//输出结果:[R(count属性:-3), R(count属性:9), R(count属性:-3), R(count属性:-2)]
hs.remove(new R(-3));//删除count为-3的R对象
System.out.println(hs);//打印结果
//输出结果:[R(count属性:-3), R(count属性:9), R(count属性:-2)]
System.out.println("hs是否包含count为-3的R对象?" + hs.contains(new R(-3)));
//输出false
//PS :因为此时的count=-3对应R对象的hascode是原来count=5的R对象对应的
System.out.println("hs是否包含count为5的R对象?" + hs.contains(new R(5)));
//输出false
//PS: 比较时不仅要比较hascode的值还要比较equals的结果
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值