JDK8
这俩个方法经常用,今天突然好奇怎么实现的,之前也看过,不过今天再来看下,记录下来
equalsIgnoreCase
List-1
1public boolean equalsIgnoreCase(String anotherString) { 2 return (this == anotherString) ? true 3 : (anotherString != null) 4 && (anotherString.value.length == value.length) 5 && regionMatches(true, 0, anotherString, 0, value.length); 6} 7 8... 9public boolean regionMatches(boolean ignoreCase, int toffset, 10 String other, int ooffset, int len) { 11 char ta[] = value; 12 int to = toffset; 13 char pa[] = other.value; 14 int po = ooffset; 15 // Note: toffset, ooffset, or len might be near -1>>>1. 16 if ((ooffset < 0) || (toffset < 0) 17 || (toffset > (long)value.length - len) 18 || (ooffset > (long)other.value.length - len)) { 19 return false; 20 } 21 while (len-- > 0) { 22 char c1 = ta[to++]; 23 char c2 = pa[po++]; 24 if (c1 == c2) { 25 continue; 26 } 27 if (ignoreCase) { 28 // If characters don't match but case may be ignored, 29 // try converting both characters to uppercase. 30 // If the results match, then the comparison scan should 31 // continue. 32 char u1 = Character.toUpperCase(c1); 33 char u2 = Character.toUpperCase(c2); 34 if (u1 == u2) { 35 continue; 36 } 37 // Unfortunately, conversion to uppercase does not work properly 38 // for the Georgian alphabet, which has strange rules about case 39 // conversion. So we need to make one last check before 40 // exiting. 41 if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) { 42 continue; 43 } 44 } 45 return false; 46 } 47 return true; 48}
如List-1所示:
- 判断是否是本身
- 判断不为空,判断长度是否相等
- 在regionMatches方法中,俩个char[]从左边开始往右边逐个对比,如果直接比较俩个字符,不相等的话,将俩个字符先都转换为大写进行比较,如果大写不相等,那么再转换为小写——注释上写着格鲁吉亚的字符有问题
equals
List-2
1public boolean equals(Object anObject) { 2 if (this == anObject) { 3 return true; 4 } 5 if (anObject instanceof String) { 6 String anotherString = (String)anObject; 7 int n = value.length; 8 if (n == anotherString.value.length) { 9 char v1[] = value; 10 char v2[] = anotherString.value; 11 int i = 0; 12 while (n-- != 0) { 13 if (v1[i] != v2[i]) 14 return false; 15 i++; 16 } 17 return true; 18 } 19 } 20 return false; 21}
- 判断是否是本身
- 判断长度,如果长度一样,那么逐个字符的比较