java中 == 与 equal 的区别

来源:互联网 发布:营改增晨曦预算软件 编辑:程序博客网 时间:2024/05/22 22:04

看一段代码:

String str1 = new String("str");String str2 = new String("str");System.out.println("==比较 :"+ (str1 == str2));System.out.println("equal比较:"+ str1.equals(str2));

结果:

==比较:falseequal比较:true

“==”和”equal”区别:

//“==”对于基本数据类型,判断两个变量的值是否相等,即数值比较,也就是用于比较变量所对应的内存中所存储的数值是否相同。
//“equal”不能用于基本数据类型。只能用于类变量。对于基本数据类型要用其包装类:

  int a=3;   int b=2;   Integer i1=new Integer(a);   Integer i2=new Integer(t2);   System.out.println(i1.equals(i2));

equals方法最初是在所有类的基类Object中进行定义的,源码是:

public boolean equals(Object obj) {    return (this == obj);}

而在String类对equals进行了重写:

public boolean equals(Object anObject) {    if (this == anObject) {        return true;    }    if (anObject instanceof String) {        String anotherString = (String)anObject;        int n = count;        if (n == anotherString.count) {        char v1[] = value;        char v2[] = anotherString.value;        int i = offset;        int j = anotherString.offset;        while (n-- != 0) {            if (v1[i++] != v2[j++])            return false;        }        return true;        }    }    return false;}

//对象引用(栈中)存储的是对象在内存(堆)中的路径,即堆地址。所以用“==”数值比较时,比较的是他们在栈的储存的内容,即使对象的值相等,但是他们引用存储的内容(栈内容)不同,所以”==”的结果为false。
//如果一个类没有自己定义equals方法,它默认的equals方法(从Object类继承的)就是使用==操作符,也是在比较两个变量指向的对象是否是同一对象,这时候使用equals和使用==会得到同样的结果

原创粉丝点击