java中equals和hashcode方法的重载

这是一个重载过的类:

class People {
private String name;

public People(String name) {
   this.name = name;
}

public String getName() {
   return name;
}
public boolean equals(Object object) {
   if (this == object) {
    return true;
   }
   if (object instanceof People) {
    People people = (People) object;
    if (name.equals(people.getName())) {
     return true;
    }
   }
   return false;
}

public int hashCode() {
   return name.hashCode();
}

}

下面是测试类:

public class SetTest {

public static void main(String[] args) {
    Set<People> set = new HashSet<People>();
    People p1 = new People("zhangsan");
    People p2 = new People("lisi");
    People p3 = new People("zhangsan");
    set.add(p1);
    set.add(p2);
    set.add(p3);
    System.out.println(p1);
    System.out.println(p2);
    System.out.println(p3);
   
    for(Iterator<People> iter = set.iterator(); iter.hasNext();) {
     System.out.println(iter.next().getName());
    }
  
    System.out.println("test".hashCode());
    System.out.println("test1".hashCode());

  
}

}

原文地址:https://www.cnblogs.com/xinzhuangzi/p/4100638.html