java "set collection to add objects"

Add three person objects to the hashSet collection, treat people with the same name as the same person, do not repeatedly add the
name and age attributes defined in the person class, and override the hashCode() method and equals() method.

package test1;
import java.text.*;
import java.util.*;
public class Main {
    
    
    public static void main(String[] args) {
    
    
                HashSet hashSet = new HashSet();
                Person p1 = new Person("Jack",25);
                Person p2 = new Person("Rose",23);
                Person p3 = new Person("Jack",27);
                hashSet.add(p1);
                hashSet.add(p2);
                hashSet.add(p3);
                for(Object obj:hashSet) {
    
    
                    Person p = (Person) obj;
                    System.out.println(p.name + ":" + p.age);
                }
    }
}
class Person{
    
    
    String name;
    int age;
    public Person(String name, int age) {
    
    
        super();
        this.name = name;
        this.age = age;
    }
    public int hashCode() {
    
    
        return name.hashCode();
    }
    //重写equals方法中传入对象的重载方法
   public boolean equals(Object obj) {
    
    
       //地址相同表示是同一个对象
        if (this == obj) {
    
    
            return true;
        }
        //传入的对象为空不是同一个对象
        if (obj == null) {
    
    
            return false;
        }
        //判断传入的对象和该类是不是同一个对象
        if(!(obj instanceof Person)){
    
    
           return false;
        }
        //把object类型转换为person类型
        Person p = (Person) obj;
        //比较两个对象的属性值是否相等
        if(p.name.equals(this.name)){
    
    
            //如果要比较多个属性值可以使用if嵌套if
            return true;
        }
        //默认返回false
        return false;
    }
}

Guess you like

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