典型回答#
这个其实不是考察你背没背过String的equals方法,而是考察你实际写一个代码的时候考虑的全不全,是不是有fail-fast的想法。
很多人第一反应就是拿出来两个字符串,for循环从头开始遍历,然后一个一个字符的比较,如果这么简单,那么就没必要问了。
其实,有很多情况可以fail fast掉,不需要比较的,比如字符串长度不一致,字符串的hashcode不一致,字符串有一个为null等等。所以,正确的判断思路是:
- 先判断对象引用
- 判断类型或 null
- 如果传入对象是
null 或类型不对,直接返回 false。
- 判断长度
- 字符串长度不同,肯定不相等,直接返回
false。
- 判断hashcode
- 字符串的hashcode不同,肯定不想等,直接返回
false。
- 逐个字符比较
- 遍历字符数组,逐位比较,如果有不同返回
false。
- 都相等
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
| public boolean myEquals(String other) {
// 1. 引用相等
if (this == other) {
return true;
}
// 2. null 判断
if (other == null) {
return false;
}
// 3. 长度判断
if (this.length() != other.length()) {
return false;
}
// 4. hashcode判断
if (this.hashCode() != other.hashCode()) {
return false;
}
// 5. 逐字符比较
for (int i = 0; i < this.length(); i++) {
if (this.charAt(i) != other.charAt(i)) {
return false;
}
}
// 6. 全部匹配
return true;
}
|