问题描述
有没有把元的数组到相应的容器对象的数组,一个优雅的方式 - 把一个字节[]
到字节]
,例如?还是我坚持了通过它循环和做手工?
Is there an elegant way to turn an array of primitives into an array of the corresponding container objects -- turn a byte[]
into a Byte[]
, for example? Or am I stuck with looping through it and doing it manually?
呀,为
循环是不完全的困难。只是有点难看。
Yeah, the for
loop isn't exactly difficult. Just kinda ugly.
推荐答案
有一个类的定义这些方法。
Apache Commons / Lang has a class ArrayUtils that defines these methods.
- 所有方法调用
toObject(...)
从原始数组转换为包装器阵列 - 所有名为
toPrimitive(...)
转换
从包装对象数组
基本数组
例如:
final int[] original = new int[] { 1, 2, 3 };
final Integer[] wrappers = ArrayUtils.toObject(original);
final int[] primitivesAgain = ArrayUtils.toPrimitive(wrappers);
assert Arrays.equals(original, primitivesAgain);
但是,我会说,包裹原语数组是不是很有用,所以你可能想看看的相反,它提供了所有数值类型的列表,由基本数组支持:
But then I'd say that Arrays of wrapped primitives are not very useful, so you might want to have a look at Guava instead, which provides Lists of all numeric types, backed by primitive arrays:
List<Integer> intList = Ints.asList(1,2,3,4,5);
List<Long> longList = Longs.asList(1L,2L,3L,4L,5L);
// etc.
的好处想想这些阵列支持的集合是
The nice think about these array-backed collections is that
- 为实时视图(即更新数组改变列表,反之亦然)
- 当需要时,才能创建包装对象(例如遍历列表时)
查看:
这篇关于转换原语的数组在Java容器的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!