Links to the original text: https://blog.csdn.net/yaomingyang/article/details/79270336
1. The equals method compares whether two strings are equal
public static boolean equals(CharSequence cs1, CharSequence cs2)
{
if (cs1 == cs2) {
return true;
}
if ((cs1 == null) || (cs2 == null)) {
return false;
}
if (cs1.length() != cs2.length()) {
return false;
}
if (((cs1 instanceof String)) && ((cs2 instanceof String))) {
return cs1.equals(cs2);
}
return CharSequenceUtils.regionMatches(cs1, false, 0, cs2, 0, cs1.length());
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
Analysis: In the source code, first use=== to compare whether two strings are equal, double sign is to compare whether the memory address of two objects is the same or whether the basic variables are equal, because the strings exist in the constant pool, so use cs1== CS2 to compare whether two strings are equal.
2. The equalsIgnoreCase method compares whether two strings are equal and ignores case.
public static boolean equalsIgnoreCase(CharSequence str1, CharSequence str2)
{
if ((str1 == null) || (str2 == null))
return str1 == str2;
if (str1 == str2)
return true;
if (str1.length() != str2.length()) {
return false;
}
return CharSequenceUtils.regionMatches(str1, true, 0, str2, 0, str1.length());
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
3. The equalsAny method returns true by comparing a string with any string in a given array
public static boolean equalsAny(CharSequence string, CharSequence... searchStrings)
{
if (ArrayUtils.isNotEmpty(searchStrings)) {
for (CharSequence next : searchStrings) {
if (equals(string, next)) {
return true;
}
}
}
return false;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
4. The equalsAnyIgnoreCase method returns true when comparing a string with any of the strings in a given array
public static boolean equalsAnyIgnoreCase(CharSequence string, CharSequence... searchStrings)
{
if (ArrayUtils.isNotEmpty(searchStrings)) {
for (CharSequence next : searchStrings) {
if (equalsIgnoreCase(string, next)) {
return true;
}
}
}
return false;
}