(十八)Java工具类StringUtils工具类compare、compareIgnoreCase方法详解

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

1.compare方法比较两个字符串是否相等,并且根据第三个参数判断null值大小

    public static int compare(String str1, String str2, boolean nullIsLess)
    {
      if (str1 == str2) {
        return 0;
      }
      if (str1 == null) {
        return nullIsLess ? -1 : 1;
      }
      if (str2 == null) {
        return nullIsLess ? 1 : -1;
      }
      return str1.compareTo(str2);
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

分析:第三个参数如果为true就判定为null值小于任何非null值;

2.compare方法比较两个字符串是否相等,调用的是上面的方法,第三个参数true

    public static int compare(String str1, String str2)
    {
      return compare(str1, str2, true);
    }
  • 1
  • 2
  • 3
  • 4

3.compareIgnoreCase方法比较两个字符串是否相等,忽略大小写

    public static int compareIgnoreCase(String str1, String str2, boolean nullIsLess)
    {
      if (str1 == str2) {
        return 0;
      }
      if (str1 == null) {
        return nullIsLess ? -1 : 1;
      }
      if (str2 == null) {
        return nullIsLess ? 1 : -1;
      }
      return str1.compareToIgnoreCase(str2);
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

4.compareIgnoreCase方法比较两个字符串的大小,默认null小于任何非空值

    public static int compareIgnoreCase(String str1, String str2)
    {
      return compareIgnoreCase(str1, str2, true);
    }

猜你喜欢

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