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!