equals与==的区别
一、==的功能是什么?
解释:== 是用于比较内存地址的。当比较对象的引用类型是,比较内存地址是否一致,从而判断对象是否相同;当比较的是基本类型的数值时,也是比较其数值存放的内存地址是否相同,数值相同的内存地址是相同的。所以总结可得==的本质就是内存地址的比较。
二、equals()的功能
1.原有功能:
equals()是Object类中的一个判断对象是否相同的方法,也就是在Object中和==是一样的功能,比较对象实例的内存地址是否相同;
2.大多数类重写后的功能(如String):
下面是String类中重写的equals(),大致就是对传入的比较参数进行字符的对比,比较字符串的内容是否一致,形成新的比较字符内容的功能,符合实际开发中的需要。重写后就是比较内容是否相同,常见的这些引用类型都已经重写了该方法,如果自己定义的类需要比较对象的内容是否一致,可以自己在声明类中重写达到需要的功能。
/**
* 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;
}
总结
以上的内容就是个人对==和equals()的一些理解,有什么不对的希望可以留言评论,共同探讨