我怎样才能在Java中连接两个数组?
我怎样才能在Java中连接两个数组?
我需要在Java中连接两个String
数组。
void f(String[] first, String[] second) { String[] both = ??? }
哪种方法最容易实现?
admin 更改状态以发布 2023年5月22日
这里是一个简单的方法,它将连接两个数组并返回结果:
publicT[] concatenate(T[] a, T[] b) { int aLen = a.length; int bLen = b.length; @SuppressWarnings("unchecked") T[] c = (T[]) Array.newInstance(a.getClass().getComponentType(), aLen + bLen); System.arraycopy(a, 0, c, 0, aLen); System.arraycopy(b, 0, c, aLen, bLen); return c; }
请注意,它只能用于对象类型而不能用于原始数据类型。以下稍微复杂一点的版本可用于对象和原始数组。它通过将T[]
替换为T
作为参数类型来实现。它还使得可以通过使用最普遍的类型作为结果的组件类型来连接两种不同类型的数组。
public staticT concatenate(T a, T b) { if (!a.getClass().isArray() || !b.getClass().isArray()) { throw new IllegalArgumentException(); } Class> resCompType; Class> aCompType = a.getClass().getComponentType(); Class> bCompType = b.getClass().getComponentType(); if (aCompType.isAssignableFrom(bCompType)) { resCompType = aCompType; } else if (bCompType.isAssignableFrom(aCompType)) { resCompType = bCompType; } else { throw new IllegalArgumentException(); } int aLen = Array.getLength(a); int bLen = Array.getLength(b); @SuppressWarnings("unchecked") T result = (T) Array.newInstance(resCompType, aLen + bLen); System.arraycopy(a, 0, result, 0, aLen); System.arraycopy(b, 0, result, aLen, bLen); return result; }
这里是一个示例:
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, concatenate(new int[] { 1, 2 }, new int[] { 3 })); Assert.assertArrayEquals(new Number[] { 1, 2, 3f }, concatenate(new Integer[] { 1, 2 }, new Number[] { 3f }));
我从好老的Apache Commons Lang库中找到了一行解决方案。ArrayUtils.addAll(T[], T...)
代码:
String[] both = ArrayUtils.addAll(first, second);