Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find difference between two integer arrays?

Tags:

java

arraylist

I'm trying to write a function which returns the difference between two arrays. The input arrays are not sorted. I'm assuming that that all elements in input arrays are unique. For Example:

Input: arr1 = [1,2,3,5,4] arr2 = [1,2,3]

Expected Output: [4,5]

I'm trying to implement this using an arraylist but can't find the problem with my code. Here it is:

public class Difference{
ArrayList<Integer> diff(int m[],int n[])
    {
        int mlen = m.length;
        int nlen = n.length;
        ArrayList<Integer> arr1 = new ArrayList<Integer>(Arrays.asList(m));
        ArrayList<Integer> arr2 = new ArrayList<Integer>(Arrays.asList(n));
        if(mlen>nlen)
        {
            arr1.removeAll(arr2);
            return arr1;
        }
        else
        {
            arr2.removeAll(arr1);
            return arr2;
        }

    }
    public static void main(String args[])
    {
          Difference obj = new Difference();
          int a[] = {1,2,3,4,5};
          int b[] = {1,2,3};
          System.out.println(obj.diff(a,b));
    }
}
like image 509
coder7777 Avatar asked Jul 31 '17 15:07

coder7777


1 Answers

The issue with your code is that you are trying to use a non-existing constructor for ArrayList(int[] numbers) You either have to add every number from m and n to the ArrayList or use a double brace initialization e.g.

ArrayList < Integer > arr1 = new ArrayList < Integer > () {
    {
        for (int i: m) add(i);
    }
}
ArrayList < Integer > arr2 = new ArrayList < Integer > () {
    {
        for (int i: n) add(i);
    }
}

In one line it would look like this without formatting

new ArrayList<Integer>() {{for(int i:m) add(i);}};

The other preferred way would be to add every number while iterating e.g.

 ArrayList<Integer> arr1 = new ArrayList<Integer>();
 for(int i: m) arr1.add(i);
like image 189
Murat Karagöz Avatar answered Oct 22 '22 17:10

Murat Karagöz