一、String的equals()源码解读:
- 比较存储的地址是否相同;
- 比较字符串的内容是否相同,也就是比较每个char是否相同。
源码:
/**
* 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; //如果变量是同一个内存地址,那值一定是相同的,返回true
}
//如果不是同一个引用,就对变量的值进行对比(比较字符串的内容是否相同,也就是比较每个char是否相同)
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;
}
二、java中equals和==的区别
- 值类型是存储在内存中的堆栈(简称栈),而引用类型(对象类似于String等)的变量在栈中仅仅是存储引用类型变量的地址,而值本身则存储在堆中。
- = =操作比较的是两个变量的值是否相等,对于引用型变量表示的是两个变量在堆中存储的地址是否相同,即比较的是栈中的内容是否相同。所以基本类型的数据比较只能用= =,因为他们只能存在栈中
- equals会先比较在栈中他们的内存地址是否相同,如果相同值就会相同,如果不同就会再去比较堆中值是否相同。
- 当equals为true时,= =有可能为true,也有可能为false。
总结:比较对象用equest,比较基本类型用= =
三、为什么八大基本数据类型放栈中 三大引用类型放堆中
- 八大基本类型的大小创建时候已经确立大小 ,三大引用类型创建时候 无法确定大小
- 堆比栈要大,但是栈比堆的运算速度要快。
- 将复杂数据类型放在堆中的目的是为了不影响栈的效率,而是通过引用的方式去堆中查找。
- 简单数据类型比较稳定,并且它只占据很小的内存,讲它放在空间小、运算速度快的栈中,能够提高效率