在HashSet集合中添加三个Person对象,把姓名相同的人当做同一个人,禁止重复添加,并且输出集合中的所有元素。

Person类中定义name和age属性,重写hashCode()方法和equals()方法,针对Person类的name属性进行比较,如果name相同,hashCode()方法的返回值相同,equals方法返回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);
        }
	}
}


猜你喜欢

转载自blog.csdn.net/deepseazbw/article/details/80224269