0

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.

Vicky
  • 1,215
  • 6
  • 22
  • 45
  • 1
    http://stackoverflow.com/questions/2728476/appending-integer-array-elements-in-java http://stackoverflow.com/questions/80476/how-to-concatenate-two-arrays-in-java – de3 May 31 '12 at 11:44

3 Answers3

3

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.)

Jon
  • 9,156
  • 9
  • 56
  • 73
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • Good point about upcasting... The implementation I wrote as an answer here will break only at runtime if you provide an Integer and a Long array... – Renato May 31 '12 at 12:03
  • Yes, that's correct; it will break. (Conversely, Apache's `ArrayUtils` will just give you an `Object[]`, which you might be able to cast with an unsafe warning, but that _is_ unsafe: it might lead to unpredictable `ClassCastException`s _later_.) – Louis Wasserman May 31 '12 at 12:06
  • Added a warning in my answer. Thanks for clarifying. – Renato May 31 '12 at 12:12
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!!

Renato
  • 12,940
  • 3
  • 54
  • 85
1

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);
tgoossens
  • 9,676
  • 2
  • 18
  • 23