Java中对象的比较 == 和 equals()

来源:互联网 发布:佳能打印软件下载 编辑:程序博客网 时间:2024/04/30 14:19
Java在对象对比时可以用符号和"=="方法 equals();
"=="符号只是单纯的比较对象引用的指针是否相等。我们知道在Java中,Object myObject 其中myObject是引用变量,是指向具体堆内存中对象的指针。也就是说Object a,b  若a == b 则说明a和b指向同一个对象,若a和b指向不同的对象,即使这两个对象完全相同,a != b
所有类都会从Object类中继承equals()方法,一般情况下equals()方法判断对象(在对内存中的实体)是否相等,如果相等则返回true,不相等则返回false。当然,具体情况还要看类的创建者是怎么重写(Override) equals()方法的。
先看一个Java系统类对象的例子
public class EqualsTest {
    
public static void main(String[] args) {
        Integer i1
=new Integer(1);
        Integer i2
=new Integer(1);
        System.out.println(i1 
== i2);
        System.out.println(i1.equals(i2));
    }

}

结果是
false
true
分析:
i1和i2虽然值相等,但它们是两个不同的引用,所以 i1 != i2
我们来看一下Java SE 6 Docs关于Integer的equals()方法的描述

equals

public boolean equals(Object obj)
Compares this object to the specified object. The result is true if and only if the argument is not null and is an Integer object that contains the same int value as this object.

 

Overrides:
equals in class Object
Parameters:
obj - the object to compare with.
Returns:
true if the objects are the same; false otherwise.

只有参数obj不为空并是Integer型,包含相同的整型值才返回true。
i1和i2符合上述条件,当然返回true了

加上自定义类,写段代码再试试

public class EqualsTest {
    
public static void main(String[] args) {
        Integer i1
=new Integer(1);
        Integer i2
=new Integer(1);
        System.
out.println(i1 == i2);
        System.
out.println(i1.equals(i2));
        MyObject m1
=new MyObject(1);
        MyObject m2
=new MyObject(1);
        System.
out.println(m1 == m2);
        System.
out.println(m1.equals(m2));
    }

}

class MyObject {
    
private int i;
     
public MyObject(int i) {
         
this.i = i;
     }

}

运行结果
false
true
false
false
分析:
m1和m2对象值完全相等,但并没有像我们想象中的结果m1.equals(m2)==true
实际上m1.equals(m2)==false 这是因为我们没有重写equals()方法,Object中默认的equals()方法和"=="一样只是判断引用指针是否相等,参看一下Object类的API Docs

所以,以上代码需要改造,加入equals()方法的重载
public class EqualsTest {
    
public static void main(String[] args) {
        Integer i1
=new Integer(1);
        Integer i2
=new Integer(1);
        System.out.println(i1 
== i2);
        System.out.println(i1.equals(i2));
        MyObject m1
=new MyObject(1);
        MyObject m2
=new MyObject(1);
        System.out.println(m1 
== m2);
        System.out.println(m1.equals(m2));
    }

}

class MyObject {
    
private int i;
     
public MyObject(int i) {
         
this.i = i;
     }

     
public boolean equals(Object obj) {
        
if(obj==null{
            
return false;
        }

        
else {
            
if(obj instanceof MyObject) {
                MyObject m 
= (MyObject)obj;
                
if(m.i==this.i) {
                    
return true;
                }

            }

        }

        
return false;
    }

}

运行结果:
false
true
false
true


 

原创粉丝点击