Java编程基础题《HashSet集合》

在HashSet集合中添加三个Person对象,把姓名相同的人当做同一个人,禁止重复添加。
要求如下:
Person类中定义name和age属性,重写hashCode()方法和equals()方法,针对Person类的name属性进行比较,如果name相同,hashCode()方法的返回值相同,equals()方法返回值为true

import java.util.*;

public class Book {
	public static void main(String[] args) {
		//定义一个HashSet集合
		HashSet hs = new HashSet();
		//创建三个Student的实例对象
		Student stu1 = new Student("a",1);
		Student stu2 = new Student("b",2);
		Student stu3 = new Student("a",3);
		//把实例对象添加到集合当中
		hs.add(stu3);
		hs.add(stu2);
		hs.add(stu1);
		System.out.println(hs);
	}
}

class Student{
	//定义私有化的name和age属性
	private String name;
	private int age;
	//定义一个构造器,为Student的name和age属性赋值
	public Student(String name,int age){
		this.name=name;
		this.age=age;
	}
	//重写toString方法
	public String toString(){
		return name+":"+age;
	}
	//重写hashCode方法,返回要去重属性的hashCode的值
	public int hashCode(){
		return name.hashCode();
	}
	//重写equals方法
	public boolean equals(Object obj){
		//判断地址是否相同,如果内存地址相同,就是同一个对象
		if(this==obj){
			return true;
		}
		//判断类型是否相同,如果类型不同则是不同的对象
		if(!(obj instanceof Student)){
			return false;
		}
		//把obj类型转化为Student类型
		Student stu=(Student) obj;
		//定义一个变量判断name的值是否相等
		boolean b = this.name.equals(stu.name);
		return b;
		
	}
}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值