String equals方法源码解析
- 前言
String类在日常编程中使用的次数较多,对于java编程来讲,String起着非常重要的作用。今天来探究一下String类里的equals的源码。基于jdk1.8. - 源码+注释
/**
* 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;
}
// 判断是否为String类型
if (anObject instanceof String) {
String anotherString = (String)anObject;
// 取出原字符串的char数组的长度
int n = value.length;
// 比较两个char的数组长度,不一样证明字符就不一样
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
// 原字符串的char数组长度递减,通过从0下标开始循环判断两个char数组相同下标下的内容是否都一样。
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
- 流程图

- 结合hashCode()
/**
* Returns a hash code for this string. The hash code for a
* {@code String} object is computed as
* <blockquote><pre>
* s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
* </pre></blockquote>
* using {@code int} arithmetic, where {@code s[i]} is the
* <i>i</i>th character of the string, {@code n} is the length of
* the string, and {@code ^} indicates exponentiation.
* (The hash value of the empty string is zero.)
*
* @return a hash code value for this object.
*/
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}
可以看注释
当char数组的长度为零的时候,hash值为默认值0
当char数组不为零的时候,hash的计算办法是
**s[0]31^(n-1) + s[1]31^(n-2) + … + s[n-1]equals和hashcode
当两个对象的equals相等,hashcode一定相等
hashcode相等的两个对象,equals不一定相等那为何重新equals后,要重写hashcode的值?
也就是说String的equals重写了之后也重写了hashcode,原因是如果没有重写hashcode,那么在判断两个对象equals相等的情况下,hashcode的计算的值就不相等,这也就违背了上面的规则。所以利用重写hashcode使得两个对象的hashcode的值相等,这样就保证了上面的规则。总结
阅读源码是了解里面的一些设计技巧,并且可以解释一些场景的理论。通过分析和扩展一些知识点,可以加强印象和思维逻辑。
版权声明:本文为weixin_45229417原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。