且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Java 中将基元数组转换为容器数组

更新时间:2022-12-15 15:18:26

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

  1. 它们是实时视图(即对数组的更新会更改列表,反之亦然)
  2. 包装对象仅在需要时创建(例如,在迭代 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 版本适用于 intlongdouble,但不适用于 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[].