我需要在Java中连接两个字符串数组。
void f(String[] first, String[] second) {
String[] both = ???
}
哪种方法最简单?
我需要在Java中连接两个字符串数组。
void f(String[] first, String[] second) {
String[] both = ???
}
哪种方法最简单?
当前回答
另一种思考问题的方式。要连接两个或多个数组,必须列出每个数组的所有元素,然后构建一个新数组。这听起来像是创建一个List<T>,然后调用它上的Array。其他一些答案使用ArrayList,这很好。但如何实现我们自己的呢?这并不难:
private static <T> T[] addAll(final T[] f, final T...o){
return new AbstractList<T>(){
@Override
public T get(int i) {
return i>=f.length ? o[i - f.length] : f[i];
}
@Override
public int size() {
return f.length + o.length;
}
}.toArray(f);
}
我相信上面的解决方案相当于使用System.arraycopy的解决方案。然而,我认为这个解决方案有其自身的优点。
其他回答
每个答案都是复制数据并创建新阵列。这并不是绝对必要的,如果您的阵列相当大,这绝对不是您想要做的。Java创建者已经知道数组拷贝是浪费的,这就是为什么他们提供System.arrayCopy()来在我们必须时在Java之外进行这些拷贝的原因。
与其四处复制数据,不如考虑将其保留在原地,并从中提取数据所在的位置。仅仅因为程序员想组织数据位置而复制数据位置并不总是明智的。
// I have arrayA and arrayB; would like to treat them as concatenated
// but leave my damn bytes where they are!
Object accessElement ( int index ) {
if ( index < 0 ) throw new ArrayIndexOutOfBoundsException(...);
// is reading from the head part?
if ( index < arrayA.length )
return arrayA[ index ];
// is reading from the tail part?
if ( index < ( arrayA.length + arrayB.length ) )
return arrayB[ index - arrayA.length ];
throw new ArrayIndexOutOfBoundsException(...); // index too large
}
另一种思考问题的方式。要连接两个或多个数组,必须列出每个数组的所有元素,然后构建一个新数组。这听起来像是创建一个List<T>,然后调用它上的Array。其他一些答案使用ArrayList,这很好。但如何实现我们自己的呢?这并不难:
private static <T> T[] addAll(final T[] f, final T...o){
return new AbstractList<T>(){
@Override
public T get(int i) {
return i>=f.length ? o[i - f.length] : f[i];
}
@Override
public int size() {
return f.length + o.length;
}
}.toArray(f);
}
我相信上面的解决方案相当于使用System.arraycopy的解决方案。然而,我认为这个解决方案有其自身的优点。
仅使用Java自己的API:
String[] join(String[]... arrays) {
// calculate size of target array
int size = 0;
for (String[] array : arrays) {
size += array.length;
}
// create list of appropriate size
java.util.List list = new java.util.ArrayList(size);
// add arrays
for (String[] array : arrays) {
list.addAll(java.util.Arrays.asList(array));
}
// create and return final array
return list.toArray(new String[size]);
}
现在,这段代码不是最有效的,但它只依赖于标准的java类,而且很容易理解。它适用于任意数量的String[](甚至是零数组)。
您可以尝试将其转换为ArrayList,然后使用addAll方法将其转换回数组。
List list = new ArrayList(Arrays.asList(first));
list.addAll(Arrays.asList(second));
String[] both = list.toArray();
使用高性能System.arraycopy而不需要@SuppressWarnings注释的通用静态版本:
public static <T> T[] arrayConcat(T[] a, T[] b) {
T[] both = Arrays.copyOf(a, a.length + b.length);
System.arraycopy(b, 0, both, a.length, b.length);
return both;
}