Possible Duplicate:
How to concatenate two arrays in Java?
I have two objects
HealthMessage[] healthMessages1;
HealthMessage[] healthMessages2;
HealthMessage[] healthMessagesAll;
healthMessages1 = x.getHealth( );
healthMessages2 = y.getHealth( );
How should I join the two objects, so I can return only one:
return healthMessagesAll;
What's the recommended way?
We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays. sort(arr) method.
In order to combine (concatenate) two arrays, we find its length stored in aLen and bLen respectively. Then, we create a new integer array result with length aLen + bLen . Now, in order to combine both, we copy each element in both arrays to result by using arraycopy() function.
You should leverage a hashmap/hashset for a substantially faster O(n) solution: void findDupes(int[] a, int[] b) { HashSet<Integer> map = new HashSet<Integer>(); for (int i : a) map. add(i); for (int i : b) { if (map. contains(i)) // found duplicate! } }
Using Apache Commons Collections API is a good way:
healthMessagesAll = ArrayUtils.addAll(healthMessages1,healthMessages2);
I'd allocate an array with the total length of healthMessages1
and healthMessages2
and use System.arraycopy
or two for
loops to copy their contents. Here is a sample with System.arraycopy
:
public class HelloWorld {
public static void main(String []args) {
int[] a = new int[] { 1, 2, 3};
int[] b = new int[] { 3, 4, 5};
int[] r = new int[a.length + b.length];
System.arraycopy(a, 0, r, 0, a.length);
System.arraycopy(b, 0, r, a.length, b.length);
// prints 1, 2, 3, 4, 5 on sep. lines
for(int x : r) {
System.out.println(x);
}
}
}
This is more intuitive to write and you don't have to deal with array indexes:
Collection<HealthMessage> collection = new ArrayList<HealthMessage>();
collection.addAll(Arrays.asList(healthMessages1));
collection.addAll(Arrays.asList(healthMessages2));
HealthMessage[] healthMessagesAll = collection.toArray(new HealthMessage[] {});
.. but don't ask me about it's performance in contrast to System.arraycopy
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With