HashSet存储自定义对象并遍历(重写hashCode()方法)

本文探讨如何使用HashSet存储自定义对象,通过重写hashCode()方法确保元素唯一性。当对象的成员变量值相同时,视为同一个元素。
摘要由CSDN通过智能技术生成


存储自定义对象,并保证元素的唯一性
如果两个对象的成员变量值都相同,则为同一个元素
 


import java.util.HashSet;

public class HashSetDemo2 {
	public static void main(String[] args) {
		HashSet<Student> hs = new HashSet<Student>();

		// 创建学生对象
		Student s1 = new Student("孙悟空", 30);
		Student s2 = new Student("唐僧", 20);
		Student s3 = new Student("猪八戒", 30);
		Student s4 = new Student("沙和尚", 40);
		Student s5 = new Student("孙悟空", 30);
		Student s6 = new Student("孙悟空", 60);

		// 把学生添加到集合
		hs.add(s1);
		hs.add(s2);
		hs.add(s3);
		hs.add(s4);
		hs.add(s5);
		hs.add(s6);

		for (Student s : hs) {
			System.out.println(s.getName() + "---" + s.getAge());
		}
	}
}

 

 

public class Student {
	private String name;
	private int age;

	public String getName() {
		return name;
	}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值