(十七)Java工具类StringUtils的equals、equalsIgnoreCase、equalsAny、equalsAnyIgnoreCase方法详解

原文链接:https://blog.csdn.net/yaomingyang/article/details/79270336

1.equals方法比较两个字符串是否相等

    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

分析:源码中首先用==比较两个字符串是否相等,双等号是比较两个对象的内存地址是否相同或者基本变量是否相等,因为字符串是存在于常量池中的所以使用cs1 == cs2来比较两个字符串是否相等;

2.equalsIgnoreCase方法比较两个字符串是否相等并且忽略大小写

    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.equalsAny方法比较字符串与给定的数组中的任何一个字符串相等就返回true

    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.equalsAnyIgnoreCase方法比较字符串与给定的数组中任何一个字符串相等就返回true

    public static boolean equalsAnyIgnoreCase(CharSequence string, CharSequence... searchStrings)
    {
      if (ArrayUtils.isNotEmpty(searchStrings)) {
        for (CharSequence next : searchStrings) {
          if (equalsIgnoreCase(string, next)) {
            return true;
          }
        }
      }
      return false;
    }

猜你喜欢

转载自blog.csdn.net/jarniyy/article/details/80414665