javaequalsapache-commons-lang3

what is the difference between equals() and equalsIgnoreCase() in StringUtils of commons-lang3-3.6.jar?


when i use this two methods, i want to know the difference,and how did equalsIgnoreCase() ignore the case of two String. But i even do not find the difference of the source code,only the order of code is different. who can help me analyze the difference of the source code,and how did it ignore case? thanks. here is the source code:

public static boolean equals(CharSequence cs1, CharSequence cs2) {
    if (cs1 == cs2) {
        return true;
    } else if (cs1 != null && cs2 != null) {
        if (cs1.length() != cs2.length()) {
            return false;
        } else {
            return cs1 instanceof String && cs2 instanceof String ? cs1.equals(cs2) : CharSequenceUtils.regionMatches(cs1, false, 0, cs2, 0, cs1.length());
        }
    } else {
        return false;
    }
}

public static boolean equalsIgnoreCase(CharSequence str1, CharSequence str2) {
    if (str1 != null && str2 != null) {
        if (str1 == str2) {
            return true;
        } else {
            return str1.length() != str2.length() ? false : CharSequenceUtils.regionMatches(str1, true, 0, str2, 0, str1.length());
        }
    } else {
        return str1 == str2;
    }
}

Solution

  • the difference is in a method CharSequenceUtils.regionMatches . The second parameter is ignoreCase

    static boolean regionMatches(CharSequence cs, boolean ignoreCase, int thisStart,
            CharSequence substring, int start, int length)    {
        if (cs instanceof String && substring instanceof String) {
            return ((String) cs).regionMatches(ignoreCase, thisStart, ((String) substring), start, length);
        } else {
            // TODO: Implement rather than convert to String
            return cs.toString().regionMatches(ignoreCase, thisStart, substring.toString(), start, length);
        }
    }