我需要在Java中连接两个字符串数组。
void f(String[] first, String[] second) {
String[] both = ???
}
哪种方法最简单?
我需要在Java中连接两个字符串数组。
void f(String[] first, String[] second) {
String[] both = ???
}
哪种方法最简单?
当前回答
这应该是一个衬垫。
public String [] concatenate (final String array1[], final String array2[])
{
return Stream.concat(Stream.of(array1), Stream.of(array2)).toArray(String[]::new);
}
其他回答
一个与类型无关的变体(已更新-感谢Volley实例化T):
@SuppressWarnings("unchecked")
public static <T> T[] join(T[]...arrays) {
final List<T> output = new ArrayList<T>();
for(T[] array : arrays) {
output.addAll(Arrays.asList(array));
}
return output.toArray((T[])Array.newInstance(
arrays[0].getClass().getComponentType(), output.size()));
}
你可以试试这个
public static Object[] addTwoArray(Object[] objArr1, Object[] objArr2){
int arr1Length = objArr1!=null && objArr1.length>0?objArr1.length:0;
int arr2Length = objArr2!=null && objArr2.length>0?objArr2.length:0;
Object[] resutlentArray = new Object[arr1Length+arr2Length];
for(int i=0,j=0;i<resutlentArray.length;i++){
if(i+1<=arr1Length){
resutlentArray[i]=objArr1[i];
}else{
resutlentArray[i]=objArr2[j];
j++;
}
}
return resutlentArray;
}
你可以键入你的数组!!!
看看这个优雅的解决方案(如果您需要除char以外的其他类型,请更改它):
private static void concatArrays(char[] destination, char[]... sources) {
int currPos = 0;
for (char[] source : sources) {
int length = source.length;
System.arraycopy(source, 0, destination, currPos, length);
currPos += length;
}
}
您可以连接每个数组计数。
ArrayList<String> both = new ArrayList(Arrays.asList(first));
both.addAll(Arrays.asList(second));
both.toArray(new String[0]);
我看到许多带有公共静态T[]concat(T[]a,T[]b){}等签名的通用答案,但据我所知,这些答案只适用于Object数组,而不适用于基元数组。下面的代码既适用于对象数组,也适用于基元数组,使其更通用。。。
public static <T> T concat(T a, T b) {
//Handles both arrays of Objects and primitives! E.g., int[] out = concat(new int[]{6,7,8}, new int[]{9,10});
//You get a compile error if argument(s) not same type as output. (int[] in example above)
//You get a runtime error if output type is not an array, i.e., when you do something like: int out = concat(6,7);
if (a == null && b == null) return null;
if (a == null) return b;
if (b == null) return a;
final int aLen = Array.getLength(a);
final int bLen = Array.getLength(b);
if (aLen == 0) return b;
if (bLen == 0) return a;
//From here on we really need to concatenate!
Class componentType = a.getClass().getComponentType();
final T result = (T)Array.newInstance(componentType, aLen + bLen);
System.arraycopy(a, 0, result, 0, aLen);
System.arraycopy(b, 0, result, aLen, bLen);
return result;
}
public static void main(String[] args) {
String[] out1 = concat(new String[]{"aap", "monkey"}, new String[]{"rat"});
int[] out2 = concat(new int[]{6,7,8}, new int[]{9,10});
}