如何在 Java 中连接两个数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/80476/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I concatenate two arrays in Java?
提问by Antti Kissaniemi
I need to concatenate two String
arrays in Java.
我需要String
在 Java 中连接两个数组。
void f(String[] first, String[] second) {
String[] both = ???
}
What is the easiest way to do this?
什么是最简单的方法来做到这一点?
回答by jeannicolas
Here's a simple method that will concatenate two arrays and return the result:
这是一个连接两个数组并返回结果的简单方法:
public <T> T[] 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;
}
Note that it will not work with primitive data types, only with object types.
请注意,它不适用于原始数据类型,只能用于对象类型。
The following slightly more complicated version works with both object and primitive arrays. It does this by using T
instead of T[]
as the argument type.
以下稍微复杂的版本适用于对象和原始数组。它通过使用T
而不是T[]
作为参数类型来做到这一点。
It also makes it possible to concatenate arrays of two different types by picking the most general type as the component type of the result.
它还可以通过选择最通用的类型作为结果的组件类型来连接两种不同类型的数组。
public static <T> T 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;
}
Here is an example:
下面是一个例子:
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 }));
回答by Antti Kissaniemi
I found a one-line solution from the good old Apache Commons Lang library.ArrayUtils.addAll(T[], T...)
我从古老的 Apache Commons Lang 库中找到了一个单行解决方案。ArrayUtils.addAll(T[], T...)
Code:
代码:
String[] both = ArrayUtils.addAll(first, second);
回答by Apocalisp
The Functional Javalibrary has an array wrapper class that equips arrays with handy methods like concatenation.
的功能的Java库具有装备有方便的方法,如级联阵列的阵列包装类。
import static fj.data.Array.array;
...and then
...进而
Array<String> both = array(first).append(array(second));
To get the unwrapped array back out, call
要取回未包装的数组,请调用
String[] s = both.array();
回答by Apocalisp
Using only Javas own API:
仅使用 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]);
}
Now, this code ist not the most efficient, but it relies only on standard java classes and is easy to understand. It works for any number of String[] (even zero arrays).
现在,这段代码不是最有效的,但它只依赖于标准的 java 类并且很容易理解。它适用于任意数量的 String[](甚至零数组)。
回答by volley
Here's an adaptation of silvertab's solution, with generics retrofitted:
这是 Silvertab 解决方案的改编版,对泛型进行了改造:
static <T> T[] concat(T[] a, T[] b) {
final int alen = a.length;
final int blen = b.length;
final T[] result = (T[]) java.lang.reflect.Array.
newInstance(a.getClass().getComponentType(), alen + blen);
System.arraycopy(a, 0, result, 0, alen);
System.arraycopy(b, 0, result, alen, blen);
return result;
}
NOTE: See Joachim's answerfor a Java 6 solution. Not only does it eliminate the warning; it's also shorter, more efficient and easier to read!
注意:有关Java 6 解决方案,请参阅Joachim 的回答。它不仅消除了警告;它也更短、更高效、更容易阅读!
回答by volley
I've recently fought problems with excessive memory rotation. If a and/or b are known to be commonly empty, here is another adaption of silvertab's code (generified too):
我最近解决了过度内存轮换的问题。如果已知 a 和/或 b 通常为空,则这里是 Silvertab 代码的另一种改编(也已生成):
private static <T> T[] concatOrReturnSame(T[] a, T[] b) {
final int alen = a.length;
final int blen = b.length;
if (alen == 0) {
return b;
}
if (blen == 0) {
return a;
}
final T[] result = (T[]) java.lang.reflect.Array.
newInstance(a.getClass().getComponentType(), alen + blen);
System.arraycopy(a, 0, result, 0, alen);
System.arraycopy(b, 0, result, alen, blen);
return result;
}
Edit: A previous version of this post stated that array re-usage like this shall be clearly documented. As Maarten points out in the comments it would in general be better to just remove the if statements, thus voiding the need for having documentation. But then again, those if statements were the whole point of this particular optimization in the first place. I'll leave this answer here, but be wary!
编辑:这篇文章的前一个版本指出,像这样的数组重用应该被清楚地记录下来。正如 Maarten 在评论中指出的那样,通常最好只删除 if 语句,从而无需拥有文档。但话又说回来,那些 if 语句首先是这个特定优化的重点。我会在这里留下这个答案,但要小心!
回答by Fabian Steeg
Using the Java API:
使用 Java API:
String[] f(String[] first, String[] second) {
List<String> both = new ArrayList<String>(first.length + second.length);
Collections.addAll(both, first);
Collections.addAll(both, second);
return both.toArray(new String[both.size()]);
}
回答by Bob Cross
If you'd like to work with ArrayLists in the solution, you can try this:
如果你想在解决方案中使用 ArrayLists,你可以试试这个:
public final String [] f(final String [] first, final String [] second) {
// Assuming non-null for brevity.
final ArrayList<String> resultList = new ArrayList<String>(Arrays.asList(first));
resultList.addAll(new ArrayList<String>(Arrays.asList(second)));
return resultList.toArray(new String [resultList.size()]);
}
回答by Bob Cross
I tested below code and worked ok
我测试了下面的代码并且工作正常
Also I'm using library: org.apache.commons.lang.ArrayUtils
我也在使用库:org.apache.commons.lang.ArrayUtils
public void testConcatArrayString(){
String[] a = null;
String[] b = null;
String[] c = null;
a = new String[] {"1","2","3","4","5"};
b = new String[] {"A","B","C","D","E"};
c = (String[]) ArrayUtils.addAll(a, b);
if(c!=null){
for(int i=0; i<c.length; i++){
System.out.println("c[" + (i+1) + "] = " + c[i]);
}
}
}
Regards
问候
回答by glue
This works, but you need to insert your own error checking.
这有效,但您需要插入自己的错误检查。
public class StringConcatenate {
public static void main(String[] args){
// Create two arrays to concatenate and one array to hold both
String[] arr1 = new String[]{"s","t","r","i","n","g"};
String[] arr2 = new String[]{"s","t","r","i","n","g"};
String[] arrBoth = new String[arr1.length+arr2.length];
// Copy elements from first array into first part of new array
for(int i = 0; i < arr1.length; i++){
arrBoth[i] = arr1[i];
}
// Copy elements from second array into last part of new array
for(int j = arr1.length;j < arrBoth.length;j++){
arrBoth[j] = arr2[j-arr1.length];
}
// Print result
for(int k = 0; k < arrBoth.length; k++){
System.out.print(arrBoth[k]);
}
// Additional line to make your terminal look better at completion!
System.out.println();
}
}
It's probably not the most efficient, but it doesn't rely on anything other than Java's own API.
它可能不是最有效的,但它不依赖于 Java 自己的 API 以外的任何东西。