Java知识总结

Java中Set(HashSet,TreeSet)知识总结

2017-09-16  本文已影响0人  ciferlv

equals()和hashCode()

使用Set类,Element必须重新定义equals(),最好同时重新定义hashCode()。
hashCode()和equals()的定义必须一致。以下定义方式来自《Java核心技术1》5.2节。

public class Employee {
    String name;
    double salary;
    LocalDate hireDay;
    public int hashCode() {
        return Objects.hash(name,salary,hireDay);
    }
}
public class Employee{
  ......
  @Override
  public boolean equals(Object otherObject) {

    if (otherObject == this) return true;
    if (otherObject == null) return false;
    if (getClass() != otherObject.getClass()) return false;
    Employee other = (Employee) otherObject;

    return Objects.equals(name, other.getName())
           &&salary==other.getSalary()
           &&Objects.equals(hireDay, other.getHireday());
  }
}

如果是在子类中定义equals(),那么就先调用超类的equals(),如下:

public class Manager extends Employee{
  ......
  @Override
  public boolean equals(Object otherObject) {

    if(!super.equals(otherObject)) return false;
    Manager other = (Manager) otherObject;
    return bonus == other.bonus;
  }
}

HashSet

TreeSet

上一篇 下一篇

猜你喜欢

热点阅读