java中set集合_java中的Set集合HashSet集合

本文通过一个Java代码示例探讨了HashSet集合的唯一性问题。当添加相同对象到HashSet时,发现相同的元素依然存在。原因是HashSet依赖对象的hashcode和equals方法进行比较,而示例中的对象没有重写这两个方法,导致默认的比较行为使HashSet无法正确识别重复元素。要实现HashSet的唯一性,必须确保对象正确重写Object类的hashcode和equals方法。
摘要由CSDN通过智能技术生成

public class HashSetDemo {

public static void main(String[] args) {

//创建集合

HashSet hash = new HashSet();

//创建学生对对象

Student s1 = new Student("one",1);

Student s2 = new Student("two",2);

Student s3 = new Student("two",2);

Student s4 = new Student("three",3);

Student s5 = new Student("four",4);

Student s6 = new Student("four",4);

Student s7 = new Student("five",5);

//添加

hash.add(s1);

hash.add(s2);

hash.add(s3);

hash.add(s4);

hash.add(s5);

hash.add(s6);

hash.add(s7);

//遍历

for(Student s : hash)

{

System.out.println(s.getAge() + s.getName());

//不是说唯一性吗?为什么打印出来发现相同的元素还是有的呢?

//原因是因为低沉用hashcode和equals方法进行比较的

//而对象却没有重写父类Object的hashcode和equals方法!所以当然不同了!

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值