您的位置:首页 > 编程语言 > Java开发

java中“==”和equal区别

2015-12-21 21:19 513 查看
8个月以后就要正式找工作啦,我觉得现在是时候花时间好好深入研究一下以前比较混肴的知识。这就当作是自我成长的第一步!

对于String中的“equal方法”和“==”一直有点混肴,今天重新看了一下他们两点的区别,记录下来让自己以后不在忘记!

先说“==”:

  “==”是用来比较两个String对象在内存中的存放地址是否相同的。例如,

String test1 = "test";
String test2 = "test";

String test3 = new String(test2);
String test4  =new String(test2);

blooean result1 = (test1==test2);
blooean result2 = (test3==test4);


其中:result1为true,result2为false。

原因:程序在运行时有一个字符串缓存机制,当String test1 = "test"的时候,程序先从缓存池中查找是否有相同的String 对象,如果有的话就不会重新生成而是用缓存池中的字符串对象;如果在字符串缓存池中没找到相同的字符串对象时才会在内存中开辟一块内存区新建字符串对象。对于test1,当test1建立以后会将“test”字符串放入缓存池中,所以运行 String test2 = "test"的时候就会直接从缓存池中取出相同的对象,也就说,test1和test2的内存地址是相同的,所以,result1是true。对于new来说,每new一次就会在内存中开辟一片内存区域,test3和test4的内存地址是不同的,所以result2是false。

再说“equal方法”:

  equal方法是object类的方法,object类中的equal方法也使用“==”实现的,也就是说,如果直接继承object类的equal方法,则也是比较两个对象在内存中的地址是否相同,但是在String中将继承自object的equal方法覆盖啦!String中的equal方法源码如下:

/**
* 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;
}


可以看出:在String中的equal方法是比较两个String对象的内容是否相同。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: