在 Java 中将基元数组转换为容器数组 [英] Converting Array of Primitives to Array of Containers in Java
问题描述
是否有一种优雅的方式将原始数组转换为相应容器对象的数组——将 byte[]
转换为 Byte[]
,例如例子?还是我一直循环遍历它并手动执行它?
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?
是的,for
循环并不难.就是有点丑.
Yeah, the for
loop isn't exactly difficult. Just kinda ugly.
推荐答案
Apache Commons
Apache Commons/Lang 有一个类 ArrayUtils 定义了这些方法.
Apache Commons / Lang has a class ArrayUtils that defines these methods.
- 所有被称为
toObject(...)
的方法从原始数组转换为包装数组 - 所有调用的
toPrimitive(...)
转换从包装对象数组到原始数组
- All methods called
toObject(...)
convert from primitive array to wrapper array - All called
toPrimitive(...)
convert from wrapper object array to primitive array
示例:
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);
<小时>
番石榴
但是我想说包装原语的数组不是很有用,所以你可能想看看 Guava 代替,它提供所有数字类型的列表,由原始数组支持:
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
- 它们是实时视图(即对数组的更新会更改列表,反之亦然)
- 包装对象仅在需要时创建(例如,在迭代 List 时)
参见:番石榴解释/原语
Java 8
另一方面,使用 Java 8 lambdas/流,您可以使这些转换变得非常简单,而无需使用外部库:
On the other hand, with Java 8 lambdas / streams, you can make these conversions pretty simple without using external libraries:
int[] primitiveInts = {1, 2, 3};
Integer[] wrappedInts = Arrays.stream(primitiveInts)
.boxed()
.toArray(Integer[]::new);
int[] unwrappedInts = Arrays.stream(wrappedInts)
.mapToInt(Integer::intValue)
.toArray();
assertArrayEquals(primitiveInts, unwrappedInts);
double[] primitiveDoubles = {1.1d, 2.2d, 3.3d};
Double[] wrappedDoubles = Arrays.stream(primitiveDoubles)
.boxed()
.toArray(Double[]::new);
double[] unwrappedDoubles = Arrays.stream(wrappedDoubles)
.mapToDouble(Double::doubleValue)
.toArray();
assertArrayEquals(primitiveDoubles, unwrappedDoubles, 0.0001d);
请注意,Java 8 版本适用于 int
、long
和 double
,但不适用于 byte
,因为 Arrays.stream() 只有 int[]
、long[]
、double[]
或通用对象 T 的重载[]
.
Note that the Java 8 version works for int
, long
and double
, but not for byte
, as Arrays.stream() only has overloads for int[]
, long[]
, double[]
or a generic object T[]
.
这篇关于在 Java 中将基元数组转换为容器数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!