我需要在Java中连接两个字符串数组。
void f(String[] first, String[] second) {
String[] both = ???
}
哪种方法最简单?
我需要在Java中连接两个字符串数组。
void f(String[] first, String[] second) {
String[] both = ???
}
哪种方法最简单?
当前回答
我测试了以下代码,工作正常
我还使用了library:org.apache.mons.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]);
}
}
}
当做
其他回答
只是想添加,您也可以使用System.arraycopy:
import static java.lang.System.out;
import static java.lang.System.arraycopy;
import java.lang.reflect.Array;
class Playground {
@SuppressWarnings("unchecked")
public static <T>T[] combineArrays(T[] a1, T[] a2) {
T[] result = (T[]) Array.newInstance(a1.getClass().getComponentType(), a1.length+a2.length);
arraycopy(a1,0,result,0,a1.length);
arraycopy(a2,0,result,a1.length,a2.length);
return result;
}
public static void main(String[ ] args) {
String monthsString = "JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC";
String[] months = monthsString.split("(?<=\\G.{3})");
String daysString = "SUNMONTUEWEDTHUFRISAT";
String[] days = daysString.split("(?<=\\G.{3})");
for (String m : months) {
out.println(m);
}
out.println("===");
for (String d : days) {
out.println(d);
}
out.println("===");
String[] results = combineArrays(months, days);
for (String r : results) {
out.println(r);
}
out.println("===");
}
}
我发现我必须处理数组可以为空的情况。。。
private double[] concat (double[]a,double[]b){
if (a == null) return b;
if (b == null) return a;
double[] r = new double[a.length+b.length];
System.arraycopy(a, 0, r, 0, a.length);
System.arraycopy(b, 0, r, a.length, b.length);
return r;
}
private double[] copyRest (double[]a, int start){
if (a == null) return null;
if (start > a.length)return null;
double[]r = new double[a.length-start];
System.arraycopy(a,start,r,0,a.length-start);
return r;
}
public static String[] toArray(String[]... object){
List<String> list=new ArrayList<>();
for (String[] i : object) {
list.addAll(Arrays.asList(i));
}
return list.toArray(new String[list.size()]);
}
允许连接多个阵列的简单变体:
public static String[] join(String[]...arrays) {
final List<String> output = new ArrayList<String>();
for(String[] array : arrays) {
output.addAll(Arrays.asList(array));
}
return output.toArray(new String[output.size()]);
}
使用流的Java8的另一种方式
public String[] concatString(String[] a, String[] b){
Stream<String> streamA = Arrays.stream(a);
Stream<String> streamB = Arrays.stream(b);
return Stream.concat(streamA, streamB).toArray(String[]::new);
}