Skip to content

Commit d44b608

Browse files
committed
fix: prevent NPE when array contains null elements
When searching for a non-null key in an array that contains null elements, the sentinel linear search would throw a NullPointerException because it called array[i].compareTo(key) without checking if array[i] is null. Added null check for array[i] in the while loop condition to prevent NPE and return the correct index when array elements themselves are null. Issue: TheAlgorithms#7318 (related)
1 parent 9729e56 commit d44b608

File tree

1 file changed

+2
-1
lines changed

1 file changed

+2
-1
lines changed

src/main/java/com/thealgorithms/searches/SentinelLinearSearch.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,8 @@ public <T extends Comparable<T>> int find(T[] array, T key) {
6565

6666
int i = 0;
6767
// Search without bound checking since sentinel guarantees we'll find the key
68-
while (array[i].compareTo(key) != 0) {
68+
// Null check for array element to prevent NPE when array contains null elements
69+
while (array[i] != null && array[i].compareTo(key) != 0) {
6970
i++;
7071
}
7172

0 commit comments

Comments
 (0)