判断String是否为空的小技巧 (转)

来源:互联网 发布:纸盒淘宝 编辑:程序博客网 时间:2024/04/28 23:09

判断String是否为空的小技巧 

Java代码 复制代码
  1.              //比较 方法一,大多数人都这么比较   
  2.   
  3.     String param = config.getInitParameter("log-level");   
  4.     if (param != null && !"".equals(param)) {   
  5.         final Level level = Log.getLevel(param);   
  6.         if (level != null) Log.lookup("org.zkoss").setLevel(level);   
  7.         else log.error("Unknown log-level: "+param);   
  8.     }   
  9.             //比较 方法二,(而我研究的源码基本都这么比较)   
  10.              String param = config.getInitParameter("log-level");   
  11.     if (param != null && param.length() > 0) {   
  12.         final Level level = Log.getLevel(param);   
  13.         if (level != null) Log.lookup("org.zkoss").setLevel(level);   
  14.         else log.error("Unknown log-level: "+param);   
  15.     }   
  16.   
  17. // 下面我们看一下equals,length,isEmpty的源码   
  18.   
  19.  //String中equals方法内部代码   
  20.   
  21.  public boolean equals(Object anObject) {   
  22. if (this == anObject) {   
  23.     return true;   
  24. }   
  25. if (anObject instanceof String) {   
  26.     String anotherString = (String)anObject;   
  27.     int n = count;   
  28.     if (n == anotherString.count) {   
  29.     char v1[] = value;   
  30.     char v2[] = anotherString.value;   
  31.     int i = offset;   
  32.     int j = anotherString.offset;   
  33.     while (n-- != 0) {   
  34.         if (v1[i++] != v2[j++])   
  35.         return false;   
  36.     }   
  37.     return true;   
  38.     }   
  39. }   
  40. return false;   
  41.    }   
  42.   
  43.   //String.length()的源码   
  44.   
  45. /**  
  46.     * Returns the length of this string.  
  47.     * The length is equal to the number of <a href="Character.html#unicode">Unicode  
  48.     * code units</a> in the string.  
  49.     *  
  50.     * @return  the length of the sequence of characters represented by this  
  51.     *          object.  
  52.     */  
  53.    public int length() {   
  54.        return count;   
  55.    }  
Java代码 复制代码
  1.    //String.isEmpty的源码   
  2.  /**  
  3.     * Returns <tt>true</tt> if, and only if, {@link #length()} is <tt>0</tt>.  
  4.     *  
  5.     * @return <tt>true</tt> if {@link #length()} is <tt>0</tt>, otherwise  
  6.     * <tt>false</tt>  
  7.     *  
  8.     * @since 1.6  
  9.     */  
  10.    public boolean isEmpty() {   
  11. return count == 0;   
  12.    }  

 

仅从代码多少以及逻辑判断来看,length,isEmpty都非常简单,对于一般比较判断来说,

 

首先我猜测:length,isEmpty是相差无几的,equals方法就望尘莫及了,

 

 

 

下面做一个测试,证明我们的猜测

 

测试代码如下

 

 

Java代码 复制代码
  1. private static final String sunflower = "sunflower";   
  2.     private static final int COUNT= 1000000000;   
  3.   
  4.     public static void main(String[] args) {   
  5.         try {   
  6.             Thread.sleep(2000);   
  7.         } catch (InterruptedException e) {   
  8.             e.printStackTrace();   
  9.         }   
  10.   
  11.         System.out.println("开始计算.../n");   
  12.   
  13.         Long begin = System.currentTimeMillis();   
  14.         for (int j = 0; j < COUNT; j++) {   
  15.             testEmptyByLength(sunflower);   
  16.         }   
  17.         calculateDuration("length test", begin);   
  18.   
  19.         begin = System.currentTimeMillis();   
  20.   
  21.         for (int j = 0; j < COUNT; j++) {   
  22.             testEmptyByEmpty(sunflower);   
  23.         }   
  24.   
  25.         calculateDuration("empty test", begin);   
  26.   
  27.         begin = System.currentTimeMillis();   
  28.   
  29.         for (int j = 0; j < COUNT; j++) {   
  30.             testEmptyByEquals(sunflower);   
  31.         }   
  32.         calculateDuration("equals test", begin);   
  33.     }   
  34.   
  35.     public static void calculateDuration(String method, long begin) {   
  36.         System.out.println(method + "/t:"  
  37.                 + (System.currentTimeMillis() - begin) / 1000);   
  38.     }   
  39.   
  40.     public static boolean testEmptyByLength(String str) {   
  41.         return str == null || str.length() < 1;   
  42.     }   
  43.   
  44.     /**  
  45.      * empty方法是jdk1.6添加的方法,如果是早期版本不兼容  
  46.      *   
  47.      * @param str  
  48.      * @return  
  49.      */  
  50.     public static boolean testEmptyByEmpty(String str) {   
  51.         return str == null || str.isEmpty();   
  52.     }   
  53.   
  54.     public static boolean testEmptyByEquals(String str) {   
  55.         return "".equals(str);   
  56.     }  
 

 

输出结果:

 

 

 

 

开始计算(s)

 

length test :0

empty test :0

equlas test :8


 

 

 

 

结论:

 

String.isEmpty()方法是jdk1.6中添加的,其方法体和length()方法一样,从性能和兼容性,length()更好,

 

所以如果对字符串非严格判断是否为空,建议使用String.length>0判断,如果严格判断是否全部为" "字符,就要自己写或者用common lang StringUtils.isBlank了

 

isBlank方法代码补充:

 

 

 

Java代码 复制代码
  1. /**  
  2.    * <p>Checks if a String is whitespace, empty ("") or null.</p>  
  3.    *  
  4.    * <pre>  
  5.    * StringUtils.isBlank(null)      = true  
  6.    * StringUtils.isBlank("")        = true  
  7.    * StringUtils.isBlank(" ")       = true  
  8.    * StringUtils.isBlank("bob")     = false  
  9.    * StringUtils.isBlank("  bob  ") = false  
  10.    * </pre>  
  11.    *  
  12.    * @param str  the String to check, may be null  
  13.    * @return <code>true</code> if the String is null, empty or whitespace  
  14.    * @since 2.0  
  15.    */  
  16.   public static boolean isBlank(String str) {   
  17.       int strLen;   
  18.       if (str == null || (strLen = str.length()) == 0) {   
  19.           return true;   
  20.       }   
  21.       for (int i = 0; i < strLen; i++) {   
  22.           if ((Character.isWhitespace(str.charAt(i)) == false)) {   
  23.               return false;   
  24.           }   
  25.       }   
  26.       return true;   
  27.   }