Converting Primitive int array to list

I am trying to solve the following problem. There are two arrays A of size n and B of size n+1. A and B have all elements same. B has one extra element. Find the element.

My logic is to convert the array to list and check if each element in B is present in A.

But when I am using the primitive arrays my logic is not working. If I am using

Integer [] a ={1,4,2,3,6,5};
Integer [] b = {2,4,1,3,5,6,7};

My code is working fine.

public static void main(String [] args)
{
    int [] a ={1,4,2,3,6,5};
    int [] b = {2,4,1,3,5,6,7};     
    List<Integer> l1 = new ArrayList(Arrays.asList(a));
    List<Integer> l2 = new ArrayList(Arrays.asList(b));
    for(Integer i :l2)
    {
        if(!l1.contains(i))
        {
            System.out.println(i);
        }           
    }
}

And also My logic is O(n+1). Is there any better algo.

Thanks

Answer

The reason it is not working for primitive arrays, is that Arrays.asList when given an int[ ] returns a List<Integer[ ]> rather than a List<Integer>.

Guava has an answer to this in the Ints class. Is has an asList method that will take an int[ ] and return a List<Integer>

Update

int[] a = ...;
int[] b = ...;
List<Integer> aList = Ints.asList(a);
List<Integer> bList = Ints.asList(b);

The above will allow your code to work properly for int[ ] as it works for Integer[ ].

Check out Ints API

Leave a Reply

Your email address will not be published. Required fields are marked *