长度为0的数组和 null
2015-12-03 12:59
801 查看
长度为0的数组 int[] arr = new int[0],也称为空数组,虽然arr长度为0,但是依然是一个对象
null数组,int[] arr = null;arr是一个数组类型的空引用。
1. 编写api方法,进行参数校验时,不要漏掉空数组的情况
比如下面这个计算递增子序列最大长度的方法,要考虑空数组的情况。
2. Effective Java第43条(返回零长度的数组或者集合,而不是null)清楚的说明了零长度或者集合的好处,可以避免调用api的客户端进行不必要的非null判断
由于该方法可能返回空,客户端调用上述方法没次都需要进行非null判断。
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判断。
相关文章推荐
- LeetCode(226)Invert Binary Tree
- static代码块 代码块 构造方法(一个参数) 构造方法(二个参数)
- LeetCode(226)Invert Binary Tree
- 常用正则
- iOS KVC & KVO
- LeetCode(226)Invert Binary Tree
- Android 编程下 Touch 事件的分发和消费机制
- [Linux] tar命令
- AngularJS处理ASP.Net MVC Json返回日期
- Android源码--多击事件
- LT8911 市面上兼容性最好的EDP桥接IC,LVDS转EDP,mipi转EDP
- 【Codeforces Round 330 (Div 2)B】【数值统计 端点思维】Pasha and Phone 电话号码 每块数是x倍数却不能以y开头方案数
- iOS 常见崩溃
- Spring中初始化bean和销毁bean的时候执行某个方法的详解
- Android学好Shape不再依赖美工
- 【Codeforces Round 330 (Div 2)A】【水题】Vitaly and Night 多少间房间有人
- [Canvas绘图] 第10节 图片加载
- Mac OS装机系列——(二)
- REDHAT YUM使用网易源
- iOS添加到购物车的简单动画效果