java中重写equals方法

来源:互联网 发布:梁朝伟张曼玉 知乎 编辑:程序博客网 时间:2024/05/19 23:18

在写java的时候难免会碰到等值问题,java中默认情况下,equals方法与 ‘==’ 是等价的,列入:

char a='d'  ;

char b='d' ;

if(a==b) System.out.println("量值相等");          运行时,程序可以正常输出,但是如下时:

String a=new String("asg");

String b=new String("asg");

if(a==b) System.out.println("量值相等");        运行时,程序就会报错。

String a="asg";

String b="asg";

if(a==b) System.out.println("量值相等");      运行时,程序正常。(该变量比较在栈中比较,栈中找到了两个变量的值,所以运行正常。而new出来的对象在堆中。上面错误)

那么,上面的具体情况又是什么?

因为String属于引用类型,而char属于基本类型,在Java中,基本数据类型(java基本数据类型包含:byte,short,int,long    float,double  boolean  和 char)是可以直接用‘==’做比较的,变量类型在栈中创建。但是引用类型,不能直接用‘==’,因为引用类型用‘==’的时候,对象在堆中创建,都会视为内存地址的比较。而在新建的引用类型对象时,new出来的对象地址并不相同,所以必须用equals。而equals的默认方法却是与‘==’等价的,那么我们就要重写这个方法。如下:

public boolean equals(object  otherobject){

if(this == otherobject)  return true;

if(otherobject instanceof String){

String otherString = (String) otherobject;

int n=count;//count:参数指定数组的长度

if(n==othertString.count){

char a[]=value;//value:字符源数组

char b[]=otherString.value;

int i=offset;//offset参数是子数组第一个字符的索引,一般默认为0

while(n--!=0){

if(a[i++] != b[i++]) {

return false;

}

return true;

}

}

return false;

}

}

0 0