Java中的==和equals的区别及用法

来源:互联网 发布:石家庄软件培训学校 编辑:程序博客网 时间:2024/06/06 02:30

最近见到的面试题中连着两次见到了==和equals,瞬间感觉这个基础的知识点还是比较重要的,故,对这个知识点进行简答的分析,如有不足请看官见谅.
原题:
String str1 = “hello”;
String str2 = “he”+ new String(“llo”);
System.err.print(str1==str2);
答案是:false.
接下来是博主对这道基础题的简单解析:

public class TestSE {
public static void main(String[] args) {
String string = “hello”;
String string2 = “he”+new String(“llo”);
System.err.println(string==string2);
System.out.println(string+string2);
System.out.println(string.equals(string2));
System.out.println(string==string);
//==比较:基本数据类型比较的是数据的值是否相等,但是string是非基本数据类型所以在比较的时候比较的是在内存中的引用
//引用指向的是在堆中开辟的新的空间,如果两个引用地址是相同的证明是相同的一块内存所存储的东西,则==判断后值为true
//equals比较的是两个数据在堆中所存放的数据是否相等,观其究竟,可以看equals的底层方法

}

}

以上程序运行的结果为:
false
hellohello
true
false
true
接下来是String.class中equals底层的方法.
public byte[] getBytes() {
return StringCoding.encode(value, 0, value.length);
}

/** * Compares this string to the specified object.  The result is {@code * true} if and only if the argument is not {@code null} and is a {@code * String} object that represents the same sequence of characters as this * object. * * @param  anObject *         The object to compare this {@code String} against * * @return  {@code true} if the given object represents a {@code String} *          equivalent to this string, {@code false} otherwise * * @see  #compareTo(String) * @see  #equalsIgnoreCase(String) */

public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n– != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
可见是对两个数据的code值进行循环比较,所以若是数据相同的话得到的结果返回的是true.
总结来说:
1,对于==,如果用来比较基本数据类型的变量,是直接比较其内存中所存储的 “值”是否相等;如果作用于引用类型的变量,则比较的是所指向的对象的引用地址是否相同.
2,equals方法是对非基本数据类型例如String类进行code值比较,注意不能用来比较基本类型.
这也解释了为什么在声明对象的时候会进行hashCode和equals方法的重写.

原创粉丝点击