Array concatenation: Difference between revisions

From Rosetta Code
Content added Content deleted
(Created task with Java)
 
(Add Python)
Line 17: Line 17:
//...list1 and list2 are instantiated...
//...list1 and list2 are instantiated...
list1And2 = new ArrayList(list1); //or any other Collection you want
list1And2 = new ArrayList(list1); //or any other Collection you want
list1And2.addAll(list2);
list1And2.addAll(list2);</lang>

=={{header|Python}}==

<lang python>arr1 = [1, 2, 3]
arr2 = [4, 5, 6]
assert arr1 + arr2 == [1, 2, 3, 4, 5, 6]</lang>

Revision as of 19:52, 9 September 2009

Task
Array concatenation
You are encouraged to solve this task according to the task description, using any language you may know.

Show how to concatenate two arrays in your language. If this is as simple as adding a list to a list, so be it.

Java

From [1]: <lang java5>public static Object[] objArrayConcat(Object[] o1, Object[] o2) {

 Object[] ret = new Object[o1.length + o2.length];

 System.arraycopy(o1, 0, ret, 0, o1.length);
 System.arraycopy(o2, 0, ret, o1.length, o2.length);

 return ret;

}</lang>

Or with Collections simply call addAll: <lang java5>Collection list1, list2, list1And2; //...list1 and list2 are instantiated... list1And2 = new ArrayList(list1); //or any other Collection you want list1And2.addAll(list2);</lang>

Python

<lang python>arr1 = [1, 2, 3] arr2 = [4, 5, 6] assert arr1 + arr2 == [1, 2, 3, 4, 5, 6]</lang>