Java programming basic questions "HashSet collection"

Add three Person objects to the HashSet collection, treat people with the same name as the same person, and do not add them repeatedly.
The requirements are as follows:
Define the name and age attributes in the Person class, override the hashCode() method and the equals() method, and compare the name attributes of the Person class. If the name is the same, the return value of the hashCode() method is the same, and the equals() method The return value is 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;
		
	}
}

Guess you like

Origin blog.csdn.net/ziyue13/article/details/109988590