Add three Person objects to the HashSet collection, treat people with the same name as the same person, prohibit repeated additions, and output all elements in the collection.

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 names are the same, the return value of the hashCode() method is the same, and the equals method returns true.


import java.lang.Object;

public 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();
     }
     public boolean equals(Object obj) {
    	 if(this==obj)
    		 return true;
    	 if(obj==null)
    		 return false;
		Person other = (Person) obj;
		return other.name.equals(this.name);   	 
     }   
}
import java.util. *;
public class Test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
        HashSet hashSet = new HashSet();
		Person p1 = new Person("tian han",20);
        Person p2 = new Person("xiao huang",20);
        Person p3 = new Person("tian han",21);
        hashSet.add(p1);
        hashSet.add(p2);
        hashSet.add(p3);
        for(Object obj:hashSet){
        	Person p =(Person) obj;
        	System.out.println(p.name+":"+p.age);
        }
	}
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325705563&siteId=291194637