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){
//返回 null 是不明智的.
// return null;
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()));
}

}