Java中判断String不为空的问题

来源:互联网 发布:卖家如何加入农村淘宝 编辑:程序博客网 时间:2024/05/16 15:48
一、判断一个字符串str不为空的方法有:

  1. str!=null;

  2. "".equals(str);

  3. str.length()!=0;

 

( 注意:length是属性,一般集合类对象拥有的属性,取得集合的大小。

            例如:数组.length就是取得数组的长度。
        length()是方法,一般字符串类对象有该方法,也是取得字符串长度。
            例如:字符串.length();

 )

 

说明:

  1. null表示这个字符串不指向任何的东西,如果这时候你调用它的方法,那么就会出现空指针异常。

  2.""表示它指向一个长度为0的字符串,这时候调用它的方法是安全的。
  3. null不是对象,""是对象,所以null没有分配空间,""分配了空间,例如:

    String str1 = null; str引用为空
    String str2 = ""; str应用一个空串

    str1还不是一个实例化的对象,儿str2已经实例化。

    对象用equals比较,null用等号比较。

    如果str1=null;下面的写法错误:
       if(str1.equals("")||str1==null){ } 
   正确的写法是 if(str1==null||str1.equals("")){ //先判断是不是对象,如果是,再判断是不是空字符串 }

 

  4. 所以,判断一个字符串是否为空,首先就要确保他不是null,然后再判断他的长度。
     String str = xxx;
     if(str != null && str.length() != 0) { }

 

 

 

二、 Java 判断字符串是否为空的三种方法的效率

    (转自网上)

 function 1: 最多人使用的一个方法, 直观, 方便, 但效率很低.
 function 2: 比较字符串长度, 效率高, 是我知道的最好一个方法.
 function 3: Java SE 6.0 才开始提供的方法, 效率和方法二几乎相等, 但出于兼容性考虑, 不推荐使用

   以下是三种方法在机器上的运行结果: (机器性能不一, 仅供参考)
 function 1 use time: 141ms
 function 2 use time: 46ms
 function 3 use time: 47ms

 

三种方法的代码如下:

  方法一:

Java代码  收藏代码
    public void function1(String s,int n) {
      long startTime = System.currentTimeMillis();
     
      for(long i = 0; i<n; i++) {
       if(s == null || s.equals(""));
      }
      long endTime = System.currentTimeMillis();
     
      System.out.println("function 1 use time: "+ (endTime - startTime) +"ms");
     }

 

 方法二:

  

Java代码  收藏代码
    public void function2(String str,int n) {
      long startTime = System.currentTimeMillis();
     
      for(long i = 0; i< n; i++) {
       if(s == null || s.length() <= 0);
      }
      long endTime = System.currentTimeMillis();
     
      System.out.println("function 2 use time: "+ (endTime - startTime) +"ms");
     }

 

方法三:

  

Java代码  收藏代码

    public void function3(String str , int n) {
      long startTime = System.currentTimeMillis();
     
      for(long i = 0; i <n; i++) {
          if(s == null || s.isEmpty());
      }
      long endTime = System.currentTimeMillis();
     
      System.out.println("function 3 use time: "+ (endTime - startTime) +"ms");
     
    }

0 0