Java实现两整数数组公共元素时出现NullPointerException问题求助
Hey there! Let's break down why you're getting that NullPointerException on the line if(array2[j] == q.peek()):
The Root Cause
When your queue q becomes empty (all elements from array1 have been either matched and removed, or discarded because they're smaller than array2[j]), calling q.peek() returns null.
Here's the critical detail: array2[j] is a primitive int, while q.peek() returns an Integer reference. Java automatically tries to unbox the Integer to an int to compare the two values—but if the Integer is null, this unboxing operation throws a NullPointerException. That's exactly what's triggering your error.
How to Fix It
The simplest fix is to add a check for whether the queue is empty before trying to access q.peek(). Once the queue is empty, there are no more elements from array1 to match, so we can exit the loop early.
Here's the updated loop section of your code:
int j = 0; while(j < array2.length && !q.isEmpty()) { // Add queue empty check here Integer peekedElement = q.peek(); if(array2[j] == peekedElement) { list.add(peekedElement); q.poll(); j += 1; } else if(array2[j] > peekedElement) { q.poll(); } else { j += 1; } }
A Quick Note on Your Algorithm
I noticed your code assumes both input arrays are sorted in ascending order. If that's not guaranteed (e.g., if array1 or array2 can be unsorted), this approach won't find all common elements. For unsorted arrays, a more reliable approach would be to use a HashSet to store elements from one array, then iterate through the other array to check for matches—this works regardless of sorting.
For example:
public static Integer[] commonElements(int[] array1, int[] array2) { Set<Integer> set = new HashSet<>(); for(int num : array1) { set.add(num); } List<Integer> common = new ArrayList<>(); for(int num : array2) { if(set.contains(num)) { common.add(num); set.remove(num); // Avoid duplicate matches if array2 has duplicates } } return common.toArray(new Integer[common.size()]); }
内容的提问来源于stack exchange,提问作者timeRocket

