zoukankan      html  css  js  c++  java
  • java ==和equals区别

    总结:在类对象中 equals()方法比较的是:对象的值,==比较的是:对象的引用(内存地址)

    例子:

    string1="aaa";

    string2="aaa";

    String string3=new String("aaa");

    String string4=new String("aaa");

    string1==string2 // true;  .

    string1.equals(string2);//true;

    string3==string4;//false   因为用new创建了2个对象,所以是两个不同的内存地址

    string3.equals(string4);//true String类的是不可改变的,所以会指向同一个内存地址,所以返回为true

    ----------------------------

       Animal  animal1=new Dog(); 
       Animal  animal2=new  Cat(); 
       Animal animal3=animal1; 

    则animal1==animal2   (FALSE) 
       animal1.equals(animal2)  (false) 
       animal1==animal3   (true) 
       animal1.equals(animal3)   (true) 

     

    equals()是object的方法,所以只是适合对象,不适合于基本类型,

    equals()默认是用"=="比较两个对象的内存地址,如果想要比较两个对象的内容,要重写equals()方法才可...

    而==:是用来判断两个对象的地址是否相同,即是否是指相同一个对象。比较的是真正意义上的指针操作。

     

    例子-重写equals():

    比如,下面Person类的equals()比较规则为:只要两个对象都是Person类,并且他们的属性name都相同,则比较结果为true,否则返回false 

    public class Person{ 
       private String name; 
       public Person(String name) 
      { 
         this.name=name; 
       } 
    public boolean equals(Object o) 
    { 
        //if (this==0) {return true}; 
        if (!o instanceof Person){ return false; }
       
        final Person other=(Person)o; 
        if (this.name().equals(other.name())) {
            return true; 
            }else { return false; }
        } 
    } 
    

     
    注意,在重写equals方法时,要注意满足离散数学上的特性 

    1、自反性   :对任意引用值X,x.equals(x)的返回值一定为true. 
    2    对称性:   对于任何引用值x,y,当且仅当y.equals(x)返回值为true时,x.equals(y)的返回值一定为true; 
    3    传递性:如果x.equals(y)=true, y.equals(z)=true,则x.equals(z)=true 
    4   一致性:如果参与比较的对象没任何改变,则对象比较的结果也不应该有任何改变 
    5   非空性:任何非空的引用值X,x.equals(null)的返回值一定为false 

     

  • 相关阅读:
    机器学习理论基础
    Python 2/3 安装与运行环境设置
    connect/express 的参考
    Koa2 的安装运行记录(二)
    iOS如何才能在招聘中表现得靠谱?
    游戏本地化不止是翻译,还有……
    IOS 判断当前UIViewController 是否正在显示
    获取iOS应用中当前处于Activity状态的ViewController
    APP UI设计趋势:为好设计而动
    实现ios后台缩略图模糊的一种方法
  • 原文地址:https://www.cnblogs.com/navy-wang/p/3338086.html
Copyright © 2011-2022 走看看