java在HashSet集合中添加三个Person对象, 姓名相同是一个人 禁止重复。Person类中定义name和age属性, 重写hashCode()和equals()方法, 针对name比较。

public class People {
String name;
int age;
@Override
public int hashCode() {//在source中寻找
	final int prime = 31;
	int result = 1;
	result = prime * result + ((name == null) ? 0 : name.hashCode());
	return result;
}
@Override
public boolean equals(Object obj) {
	if (this == obj)
		return true;
	if (obj == null)
		return false;
	if (getClass() != obj.getClass())
		return false;
	final People other = (People) obj;
	if (name == null) {
		if (other.name != null)
			return false;
	} else if (!name.equals(other.name))
		return false;
	return true;
}
public People(String name, int age) {
	
	this.name = name;
	this.age = age;
}	}

import java.util.HashSet;
public class Test_P {
	public static void main(String[] args) {
		People p1=new People("张三",20);
		People p2=new People("李四",21);
		People p3=new People("王五",20);	
		HashSet set=new HashSet();
		set.add(p1);
		set.add(p2);
		set.add(p3);	
		System.out.println("一共有"+set.size()+"名员工!");
		for(Object a:set){
			People p=(People)a;
			System.out.println(p.name+"~"+p.age);			
		}
	}
}
  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值