站点微信订阅号zhengjinyibu,欢迎大家搜索关注.
Collections.emptyList().toArray(new Person[0]);
此处可以参考阿里Java编程规范手册
使用toArray带参方法,入参分配的数组空间不够大时,toArray方法内部将重新分配内存空间,并返回新数组地址;如果数组元素大于实际所需,下标为[ list.size() ]的数组元素将被置为null,其它数组元素保持原值,因此最好将方法入参数组大小定义与集合元素个数一致。
Collections.emptyList()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| package com.canal.demo;
import com.alibaba.fastjson.JSON; import com.google.common.collect.Lists;
import java.util.Collection; import java.util.Collections; import java.util.List;
public class ZookeeperHello {
private static boolean empty=true;
private static class Person{ private String name;
public Person(String name) { this.name = name; }
public String getName() { return name; }
public void setName(String name) { this.name = name; } }
private static Person[] getPersonArray(){ if(empty){
return Collections.emptyList().toArray(new Person[0]); } List<Person> personList =Lists.newArrayList(new Person("array")); return personList.toArray(new Person[personList.size()]); }
private static Collection<Person> getPersonCollection(){ if(empty){ return Collections.emptyList(); } return Lists.newArrayList(new Person("collection")); }
public static void main(String[] args) { System.out.println(JSON.toJSON(getPersonArray())); System.out.println(JSON.toJSON(getPersonCollection())); }
}
|
本文内容仅作为作者个人兴趣与观点,不代表所在公司及团队的观点和决策。若有不恰当之处,请联系站长.