长度为0的数组和 null

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

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

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

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

public class Solution {
    public int lengthOfLIS(int[] nums) {
        if (nums == null || <span style="color:#ff0000;">nums.length == 0</span>) {
            return 0;
        }

        int size = nums.length;
        int[] itemLengthArray = new int[size];
        int currentMax = 0;
        int outMax = 1;
        for (int k = 0 ; k < size; ++k) {
            itemLengthArray[k] = 1;
        }
        
        for (int i = 1; i < size; ++i) {
            for (int j = 0; j < i; ++j) {
                if (nums[j] < nums[i]) {
                    if (currentMax < itemLengthArray[j]) {
                        currentMax = itemLengthArray[j];
                    }
                }
            }
            itemLengthArray[i] = currentMax + 1;
            currentMax = 0;
            outMax = outMax > itemLengthArray[i] ? outMax : itemLengthArray[i];
        }
        return outMax;
    }
}

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

public String[] getIpList() {
    if (ipList.size != 0) {
        ......
    }
    return null;
}

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

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值