• java重写equals方法


    重写equals: 比较内容。

    hashCode: 内容的hashCode()。


    /*

    * 重写equals必须注意:
    * 1 自反性:对于任意的引用值x,x.equals(x)一定为true
    * 2 对称性:对于任意的引用值x 和 y,当x.equals(y)返回true,y.equals(x)也一定返回true
    * 3 传递性:对于任意的引用值x、y和z,如果x.equals(y)返回true,并且y.equals(z)也返回true,那么x.equals(z)也一定返 回 true
    * 4 一致性:对于任意的引用值x 和 y,如果用于equals比较的对象信息没有被修改,
    * 多次调用x.equals(y)要么一致地返回true,要么一致地返回false
    * 5 非空性:对于任意的非空引用值x,x.equals(null)一定返回false
    * 
    * 请注意:
    * 重写equals方法后最好重写hashCode方法,否则两个等价对象可能得到不同的hashCode,这在集合框架中使用可能产生严重后果
    */


    /*
    * 1.重写equals方法修饰符必须是public,因为是重写的Object的方法.
    * 2.参数类型必须是Object.
    */
    public boolean equals(Object other){ //重写equals方法,后面最好重写hashCode方法

    if(this == other) //先检查是否其自反性,后比较other是否为空。这样效率高
    return true;
    if(other == null)
    return false;
    if( !(other instanceof Cat))
    return false;

    final Cat cat = (Cat)other;

    if( !getName().equals(cat.getName()))
    return false;
    if( !getBirthday().equals(cat.getBirthday()))
    return false;
    return true;
    }

    public int hashCode(){ //hashCode主要是用来提高hash系统的查询效率。当hashCode中不进行任何操作时,可以直接让其返回 一常数,或者不进行重写。
    int result = getName().hashCode();
    result = 29 * result +getBirthday().hashCode();
    return result;
    //return 0;
    }

    @Override
    public boolean equals(Object obj) {
    if (obj instanceof XComparatorSource) {
    XComparatorSource other = (XComparatorSource) obj;
    if (other.key.equals(this.key)) {
    return true;
    }
    }
    return false;
    }

    @Override
    public int hashCode() {
    return key.hashCode();
    }

    http://blog.csdn.net/min123456520/article/details/5194030

  • 相关阅读:
    The AllegroGraph Tutorial
    Using Prolog withUsing Prolog with AllegroGraph 7.1.0 AllegroGraph 7.1.0
    Prolog 语言入门教程
    Learn Prolog Now!:Chapter 3 Recursion
    What are OWL Ontologies?
    论文阅读:SkillMaN—A skill-based robotic manipulation framework based on perception and reasoning
    论文阅读:Knowledge-based instruction of manipulation tasks for industrial robotics
    Learn Prolog
    KnowRob安装过程中的相关问题记录
    Qt音视频开发17-海康sdk解码
  • 原文地址:https://www.cnblogs.com/ydxblog/p/5582859.html
Copyright © 2020-2023  润新知