日期:2014-05-20  浏览次数:20666 次

Set接口问题2
Java code
import java.util.*;

public class HashSetDemo02 {
    public static void main(String[] args) {
        Set<Person> allset = new HashSet<Person>();
        allset.add(new Person("张三",20));
        allset.add(new Person("李四",21));
        allset.add(new Person("李四",21));
        allset.add(new Person("李四",21));
        allset.add(new Person("李四",21));
        System.out.println(allset);
    }

}
Person {
    private String name;
    private int age;
    public Person(String name, int age) {
        this.setName(name);
        this.setAge(age);
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    //覆写equels()方法和hashCode()方法
    public boolean equels(Object obj){
        if(this == obj){
            return true;
        }
        if(!(obj instanceof Person)){
            return false;
        }
        Person p = (Person)obj;
        if(this.name.equals(p.name) && this.age == p.age){
            return true;
        }else{
            return false;
        }
    }
    public int hashCode(){
        return this.name.hashCode()*this.age;//指定公式
    }
    public String toString(){
        return "姓名:" + this.getName() + "年龄:" + this.getAge();
    }
}


覆写了Object的equels()和hashCode()方法,可以去掉重复元素,可是结果没有去掉,为什么?

------解决方案--------------------
Java code

public boolean equals(Object obj){  //---是equals而不是equels
        if(this == obj){
            return true;
        }
        if(!(obj instanceof Person)){
            return false;
        }
        Person p = (Person)obj;
        if(this.name.equals(p.name) && this.age == p.age){
            return true;
        }else{
            return false;
        }
    }

------解决方案--------------------
如果是想override,在方法上加上@Override注解就可以避免很多错误
------解决方案--------------------
不要复写 直接添加