最近在看《 Effective Java 》这本书,里面提到了编码时需要注意【 不要返回NULL(Rule439) 】,这里备份下实现的注意点,截图版权属于原作者。
github:
【 https://github.com/cstriker1407/think_in_java 】
下面备份下返回数组和返回List等方法:
class Rule43Bean { //sth } class NullClass { private static final Rule43Bean[] emptyArray = new Rule43Bean[0]; private List<Rule43Bean> list = new ArrayList<Rule43Bean>(); /*some methods*/ //返回数组 public Rule43Bean[] getArrs() { return list.toArray(emptyArray); } //返回list public List<Rule43Bean> getList() { if (list.isEmpty()) {//返回空的list return Collections.emptyList(); }else {//保护性拷贝 return new ArrayList<Rule43Bean>(list); } } }
原书介绍:
发表评论