这可能是一个愚蠢的问题,但是foo()和之间有什么区别bar()吗?
private static File[] foo() {
return Collections.emptyList().toArray(new File[0]);
}
Run Code Online (Sandbox Code Playgroud)
private static File[] bar() {
return new File[0];
}
Run Code Online (Sandbox Code Playgroud)
我试图想出返回空数组的最佳方法,而不是null.
Pet*_*rey 76
返回空数组的另一种方法是使用常量,因为给定类型的所有空数组都是相同的.
private static final File[] NO_FILES = {};
private static File[] bar(){
return NO_FILES;
}
Run Code Online (Sandbox Code Playgroud)
wee*_*ens 32
双方foo()并bar()可能产生一些IDE的警告.例如,IntelliJ IDEA将生成Allocation of zero-length array警告.
另一种方法是使用ArrayUtils.toArray()带有空参数的Apache Commons Lang 3 函数:
public File[] bazz() {
return ArrayUtils.toArray();
}
Run Code Online (Sandbox Code Playgroud)
这种方法既性能又适合IDE,但需要第三方依赖.但是,如果你的类路径中已经有commons-lang3,你甚至可以使用静态定义的空数组来表示原始类型:
public String[] bazz() {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*aux 18
绝对是第二个.在第一个中,使用常量为空List<?>,然后将其转换为a File[],这需要创建一个空File[0]数组.这就是你在第二步中所做的一步.
您可以通过以下两种方式返回空数组:
如果要返回的数组int则
使用{}:
int arr[] = {};
return arr;
Run Code Online (Sandbox Code Playgroud)使用new int[0]:
int arr[] = new int[0];
return arr;
Run Code Online (Sandbox Code Playgroud)同样,您也可以为其他数据类型返回数组。
| 归档时间: |
|
| 查看次数: |
123859 次 |
| 最近记录: |