0

I am trying to write a program that finds the common numbers in 2 integer arrays.

Here is my code:

public static Integer[] commonElements(int[] array1, int[] array2) {
        Queue<Integer> q = new LinkedList<Integer>();
        ArrayList<Integer> list = new ArrayList<Integer>();
        for(int i: array1){
            q.add(i);
        } //O(N)
        int j = 0;
        while(j < array2.length){
            if(array2[j] == q.peek()){
                list.add(q.peek());
                q.poll();
                j += 1;
            }
            else if(array2[j] > q.peek()){
                q.poll();
            }
           else{
            j += 1; 
          }
        }
        Integer[] resultInArray = list.toArray(new Integer[list.size()]);
        return resultInArray;

    }
}

But I keep getting the null pointer exception on this line here if(array2[j] == q.peek()), I know that the null pointer exception occurs when one of the two objects I am comparing is null, but I don't see how in this circumstance which one it is. Can anyone see what is creating the null here? Thank you!

timeRocket
  • 93
  • 1
  • 1
  • 9
  • 2
    @JohnKugelman q.peek() can return null and result in nullpointer – Derrick May 28 '18 at 12:53
  • @JohnKugelman could in theory happen in a multi-threaded environment I guess. But that's rather unlikely, I agree. – Ben May 28 '18 at 12:53
  • I see. So the null comes from q.peek(). Thanks a lot! – timeRocket May 28 '18 at 12:57
  • 1
    `q` isn't null, you clearly initialize it to a `new LinkedList`. `array2` can't be null; if it were, accessing `array2.length` on the previous line would have crashed. The culprit must be `q.peek()`: when the queue is empty `peek()` returns null, and unboxing a null will result in a null pointer exception. – John Kugelman May 28 '18 at 12:58

0 Answers0