// how to convert this
Integer[] array = {1, 2};
// to this
int[] array = {1, 2};
Run Code Online (Sandbox Code Playgroud)
我正在处理具有第二种形式的代码,我需要修改数组的读取方式.不太了解Java,我宁愿只转换风险错误.
Boz*_*zho 10
你可以使用commons-lang ArrayUtils.toPrimitive(array)
如果您出于某种原因不想包含commons-lang,那么这是该方法的代码.但是,只包含依赖项是一个更好的选择 - 它有许多你最终需要的附加功能.
public static final int[] EMPTY_INT_ARRAY = new int[0];
public static int[] toPrimitive(Integer[] array) {
if (array == null) {
return null;
}
if (array.length == 0) {
return EMPTY_INT_ARRAY;
}
int[] result = new int[array.length];
for (int i = 0; i < array.length; ++i) {
result[i] = array[i].intValue();
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
260 次 |
| 最近记录: |