# help: union of two array,.. kinda problem

• November 26th, 2009, 01:55 AM
sanfor
help: union of two array,.. kinda problem
hello guys..
i'm new here.
i am trying to do a function that unite two arrays.

this is my code:

arr4 = interSection = gets the intersection of the two arrays.

arr1,arr2 = similar... = reduce the repetition..

i don't see "errors" in the code itself but when i run it.. i get this:

Code :

```Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7 at Even.union(Even.java:64) at Even.main(Even.java:33)```

which is this line (64):
Code :

` arr3[arr1.length+i]=arr2[i-1];`

Code :

``` public static int[] union(int[] arr1,int[] arr2) {     int[] arr4 = interSection(arr1,arr2);   arr1 = Similar(arr1); arr2 = Similar(arr2);   int[] arr3 = new int[arr1.length+arr2.length-arr4.length];   for (int i=0;i < arr1.length;i++) arr3[i]=arr1[i];   for (int i=1;i<=arr2.length;i++) arr3[arr1.length+i]=arr2[i-1];       return Similar(arr3);   }```
• November 26th, 2009, 02:31 AM
Json
Re: help: union of two array,.. kinda problem
You always need to be careful when you play with array indexes, especially if you use the plus sign when calculating the index.

Code :

`arr1.length+i`

This piece of code above will most likely cause an issue if you're not 100% sure of what the value can be.

You call a method interSection which does what?

The things you need to be aware of is the length of each array and if the interSection is returning an array thats too big then the length of arr3 will be too short because you use arr4 when initialising arr3 and its length.

I'm sorry I can't be much more of help but if you'd like a better way of adding one array onto another then give us a shout.

// Json
• November 29th, 2009, 01:33 PM
sanfor
Re: help: union of two array,.. kinda problem
well.. thanks for the reply..
``` public static int[] union(int[] arr1,int[] arr2) {   int[] arr3 = new int[arr1.length+arr2.length];   System.arraycopy(arr1, 0, arr3, 0, arr1.length); System.arraycopy(arr2, 0, arr3, arr1.length, arr2.length);   return arr3;   }```