日期:2014-05-20  浏览次数:21059 次

又是==和equals(100分)
不行了,搞不懂,请教

据查Object类的equals()定义如下:
public   boolean   equals(Object   x)
{
    return   this==x;//   其最终还是用“==”比较,因此两个对象比较真值要重载重写       equals,但是下面的测试结果就很耐人寻味
}

  a和z1有什么区别,一个是分配了堆空间,一个是栈?或者a是一个指向堆空间的指针而z1难道就不是指针了吗?它们之间的分别难道源自“=”的运算符重载调用了不同的成员函数?

注意:下面的结果都经过测试,equals没有进行重写!

Try   x1=new   Try( "aafasf ");
        Try   x2=new   Try( "aafasf ");

        String   a=new   String( "asdsfa ");
        String   b=new   String( "asdsfa ");
        String   c=new   String( "asdsfl ");
       
        String   z1= "asdsfa ";
        String   z2= "asdsfa ";
        String   z3= "asdsfl ";
-----------------------
        if(x1==x2)                                                                       //no,这个不用说
              System.out.print( "t     String   ok\n ");                    
        else  
              System.out.print( "t     String   no\n ");
-----------------------
        if(a==b)                                                                           //no,    
              System.out.print( "a,b     Stringnew   ok\n ");
        else  
              System.out.print( "a,b     Stringnew   no\n ");

a和b是个指向空间的指针(句柄)那么就没问题了,但是a.equals(b)怎么就为真呢?
因为实质上也是“==”

-----------------------        
        if(a==c)                                                                           //no
              System.out.print( "a,c     Stringnew   ok\n ");
        else  
              System.out.print( "a,c     Stringnew   no\n ");
是地址比较还是真值比较呢?应该是地址吧
-----------------------
        if(z1==z2)                                                                       //ok
              System.out.print( "a,b     String   ok\n ");