How to append entire second array to first array in java

ε祈祈猫儿з 提交于 2019-12-11 18:22:07

问题


I know, We can copy or append elements of array. But, I have around 100 elements in an array. Is there any other way available so I can append array to first array.

Consider I have this two arrays.

 String name1[]={"abc", "def", "ghi"};
 String name2[]={"jkl", "mno", "pqr"};

I want to append name2 array at the end of name1.

Please help me.

would be grateful for help.


回答1:


Guava provides Arrays.concat(T[], T[], Class<T>).

The reason for the Class parameter, FYI, is because generic arrays have a distinct tendency to get upcast. If you did Arrays.concat(Integer[], Long[]), did you want an Object[] back? Or a Number[]? Guava makes you specify so there's no ambiguity...and because all of the alternatives can lead to unpredictable ClassCastExceptions at runtime.

(Disclosure: I contribute to Guava.)




回答2:


You will have to create a new array.

An easy implementation using generics and not using any external library:

public static void main(String[] args) {
    String [] a1 = { "a", "b" };
    String [] a2 = { "c", "d", "e", "f" };

    System.out.println(Arrays.toString(append(a1, a2)));
}

public <K> K[] append(K[] a1, K[] a2) {
    K[] a1a2 = Arrays.copyOf(a1, a1.length + a2.length);
    for (int i = a1.length; i < a1a2.length; i++) {
        a1a2[i] = a2[i - a1.length];
    }
    return a1a2;
}

OBS: As Louis Wasserman comments in his answer, Java will upcast the arrays, which can be a problem. For example, if you provide a Long[] and an Integer[] to the append method above, it will compile but you will get a java.lang.ArrayStoreException at run-time!!




回答3:


You will have to create a new array. Because the length of arrays is fixed.

 String[] list = new String[name1.length+name2.length]

You could loop around the two arrays and add each element to the new array

You could also use apache commons lang library

 String[] both = ArrayUtils.addAll(first, second);


来源:https://stackoverflow.com/questions/10832902/how-to-append-entire-second-array-to-first-array-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!