字符串判断为空

判断一个字符串是否为空方法有三种
  1. str!=null
  2. “”.equal(str)
  3. str.length()!=0
(注意:length是属性,一般集合类对象拥有的属性,取得集合的大小。例如:数组.length表示数组的属性取得数组的长度
length()是方法,一般字符串对象有该方法,也是取得字符串的长度。例如:字符串.length()  
在java中有()的表示方法,没有的表示属性)
说明:
  1. null表示这个字符串不指向任何的东西,如果这时候调用它的话,会报空指针异常
  2. “”表示它指向一个长度为0的字符串,这个时候调用它是安全的
  3. null不是对象,“”是对象,所以null没有分配空间,“”分配了空间。例如
      String str1=null;    str引用为空
  String str2=“”;     stri引用一个空串
  4. 所以,判断一个字符串是否为空的时候,要先确保他不是null,然后在判断他的长度。   String str=”xxx”;   if(str!=null && str.lengt>0)
 

以下是代码测试
public class TestEmpty {
    public static Long function1(int n, String s) {
        long startTime = System.nanoTime();
        for (int i = 0; i < n; i++) {
            if (s == null || "".equals(s))
                ;
        }

        long endTime = System.nanoTime();
        return endTime - startTime;
    }

    public static Long function2(int n, String s) {
        long startTime = System.nanoTime();
        for (int i = 0; i < n; i++) {
            if (s == null || s.length() <= 0)
                ;
        }
        long endTime = System.nanoTime();
        return endTime - startTime;
    }

    public static Long function3(int n, String s) {
        long startTime = System.nanoTime();
        for (int i = 0; i < n; i++) {
            if (s == null || s.isEmpty())
                ;
        }
        long endTime = System.nanoTime();
        return endTime - startTime;
    }

    public static void main(String[] args) {
        String s = "ss";
        for (int i = 0; i < 20; i++) {
            System.out.println(function1(1000, s)); // 90788
            System.out.println(function2(1000, s)); // 22499
            System.out.println(function3(1000, s)); // 33947
            System.out.println("---------------------------");
        }
    }
 
当循环次数在100以下的时候function2和 function3的用时差不多,
当达到1000的时候明显function2的时间较少,建议使用s == null || s.length() <= 0;测试过判断不为空的方法也是s!=null&&s.length>0的时间较短

本文大部分参考

原文地址:https://www.cnblogs.com/dashuai01/p/4766117.html