Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join two arrays in Java? [duplicate]

Tags:

java

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?

like image 254
Danijel Avatar asked Nov 27 '12 11:11

Danijel


People also ask

How do you remove duplicates from two arrays in Java?

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.

How do I combine two arrays?

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.

How do you find duplicates in two arrays in Java?

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! } }


3 Answers

Using Apache Commons Collections API is a good way:

healthMessagesAll = ArrayUtils.addAll(healthMessages1,healthMessages2);
like image 161
Chexpir Avatar answered Oct 04 '22 21:10

Chexpir


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);
        }            
     }         
}
like image 41
Matthias Meid Avatar answered Oct 04 '22 23:10

Matthias Meid


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.

like image 24
Kai Avatar answered Oct 04 '22 22:10

Kai