Merging Array of Primitives

This is (supposedly) a trivial question: how to merge 2 arrays of primitives, avoiding duplicate elements?

One simple option is to create an ArrayList, and add the elements one by one, making sure you’re not adding an element that already exists in the list. Another one, simpler again, is to use a Set, and add the elements one by one: the Set (such as HashSet) ensures there is no duplicate.

But you want to avoid loops, and adding elements one by one. You want to use addAll. and that’s where the fun begins.

There is no auto(un)boxing of arrays in Java; in other words, int[] doesn’t automagically become Integer[], and Integer[] doesn’t become int[]. This means you have to do it yourself, by doing something like:

	private static Integer[] toObjectArray(int[] array) {
		Integer[] objectArray = new Integer[array.length];

		int index = 0;
		for (int i: array) {
			objectArray[index] = i;
			index++;
		}

		return objectArray;
	}

	private static int[] toPrimitiveArray(Integer[] objectArray) {
		int[] array = new int[objectArray.length];

		int index = 0;
		for (int i: objectArray) {
			array[index] = i;
			index++;
		}

		return array;		
	}

The other possibility is to use Apache Commons Lang.

Once you have this, the original assignment is straightforward:

public class MergeArrays {

		// Previous methods toObjectArray and toPrimitiveArray...

	public static void main(String[] args) {
		int a[] = { 5, 6, 7, 8, 9 };
		int b[] = { 1, 2, 3, 4, 5, 6, 7, 8 };

		Set<Integer> set = new HashSet<Integer>();
		set.addAll(Arrays.asList(toObjectArray(a)));
		set.addAll(Arrays.asList(toObjectArray(b)));

		int c[] = toPrimitiveArray(set.toArray(new Integer[set.size()]));
		System.out.println(Arrays.toString(c));
	}
}
 
---

Comment

your_ip_is_blacklisted_by sbl.spamhaus.org

---