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;
		
	}
}

猜你喜欢

转载自blog.csdn.net/ziyue13/article/details/109988590