美文网首页Java知识总结
Java中Set(HashSet,TreeSet)知识总结

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

作者: ciferlv | 来源:发表于2017-09-16 22:27 被阅读0次

    equals()和hashCode()

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

    • boolean equals( Object otherObject ) 比较两个对象是否相等,若两个对象指向同一块存储区域,返回true,否则返回false.
    • 定义hashCode():
    public class Employee {
        String name;
        double salary;
        LocalDate hireDay;
        public int hashCode() {
            return Objects.hash(name,salary,hireDay);
        }
    }
    
    • 定义boolean equals( Object otherObject )
    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

    • HashSet必须重定义Element的hashCode()函数。
    • HashSet依据两个Object的Hash值来判断Element是否相等。

    TreeSet

    • 使用TreeSet的Element必须定义比较器,可以使implements Comparable,也可以 implements Comparator。
    • TreeSet不仅会拒绝Hash值相等的Element,同时也会拒绝所定义的比较器认为相等的Element。
    • 参考1

    相关文章

      网友评论

        本文标题:Java中Set(HashSet,TreeSet)知识总结

        本文链接:https://www.haomeiwen.com/subject/xnyusxtx.html