长度为0的数组 int[] arr = new int[0],也称为空数组,虽然arr长度为0,但是依然是一个对象 String str="";长度为0,但是不是null。String str=null;此时不能调用长度方法。没有长度这么一说

长度为0的数组和 null

package testjavase;

public class Test01 {

    /**
     * @param args
     */
    public static void main(String[] args) {
            String[] s =new String[0] ;
            for(String c : s)
                    
                System.out.println(c);
            System.out.println(s.length);
                    for (int i = 0 ; i<s.length ; i++){
                        System.out.println(s[i]+",");
            }
                    String str="";
                    System.out.println(str);
                    System.out.println(str.length());
    }

}

 

package testjavase;

public class Test01 {

    /**
     * @param args
     */
    public static void main(String[] args) {
            String[] s =new String[0] ;
            for(String c : s)
                    
                System.out.println(c);
            System.out.println(s.length);
                    for (int i = 0 ; i<s.length ; i++){
                        System.out.println(s[i]+",");
            }
    
    }

}

空字符串数组,不报错,没有输出,数组长度为0.

长度为0的数组 int[] arr = new int[0],也称为空数组,虽然arr长度为0,但是依然是一个对象

null数组,int[] arr = null;arr是一个数组类型的空引用。

1. 编写api方法,进行参数校验时,不要漏掉空数组的情况

比如下面这个计算递增子序列最大长度的方法,要考虑空数组的情况。

[java] view plain copy
  1. public class Solution {  
  2.     public int lengthOfLIS(int[] nums) {  
  3.         if (nums == null || <span style="color:#ff0000;">nums.length == 0</span>) {  
  4.             return 0;  
  5.         }  
  6.   
  7.         int size = nums.length;  
  8.         int[] itemLengthArray = new int[size];  
  9.         int currentMax = 0;  
  10.         int outMax = 1;  
  11.         for (int k = 0 ; k < size; ++k) {  
  12.             itemLengthArray[k] = 1;  
  13.         }  
  14.           
  15.         for (int i = 1; i < size; ++i) {  
  16.             for (int j = 0; j < i; ++j) {  
  17.                 if (nums[j] < nums[i]) {  
  18.                     if (currentMax < itemLengthArray[j]) {  
  19.                         currentMax = itemLengthArray[j];  
  20.                     }  
  21.                 }  
  22.             }  
  23.             itemLengthArray[i] = currentMax + 1;  
  24.             currentMax = 0;  
  25.             outMax = outMax > itemLengthArray[i] ? outMax : itemLengthArray[i];  
  26.         }  
  27.         return outMax;  
  28.     }  
  29. }  

 

2. Effective Java第43条(返回零长度的数组或者集合,而不是null)清楚的说明了零长度或者集合的好处,可以避免调用api的客户端进行不必要的非null判断

 

[java] view plain copy
  1. public String[] getIpList() {  
  2.     if (ipList.size != 0) {  
  3.         ......  
  4.     }  
  5.     return null;  
  6. }  

由于该方法可能返回空,客户端调用上述方法没次都需要进行非null判断。

posted on 2016-06-26 04:07  雪的心  阅读(856)  评论(0编辑  收藏  举报

导航