Cannot use Arrays.sort()
for Integer
type array if it has null elements. Unlike int
type array, null
values are not assigned to 0.
How to sort the Integer
type array if it has a null
element?
Integer[] arr=new Integer[4] {6,7,null,null};
I want to sort this arr
array variable.
The error is as follows:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Comparable.compareTo(Object)" because "a[runHi]" is null
at java.base/java.util.ComparableTimSort.countRunAndMakeAscending(ComparableTimSort.java:320)
at java.base/java.util.ComparableTimSort.sort(ComparableTimSort.java:188)
at java.base/java.util.Arrays.sort(Arrays.java:1040)
at Example.medicinePriceForGivenDisease(Example.java:41)
at Example.main(Example.java:21)
Since Integer
is a Comparable
, you can use the overloaded Arrays.sort(Object[])
. Ie:
Integer[] arr = new Integer[4]; //not "int"
// fill in some data in arr
Arrays.sort(arr);
The java.util.Arrays
class has all required methods for sorting, including sort(Object[] a)
. Since Integer
is an object, it will do nicely:
Integer[] arr = new Integer[] { 32, 12, 9, 77 };
Arrays.sort(arr);
// Array sorted it
The single parameter Arrays.sort(Object[])
sorts elements that must implement the Comparable
interface using the compareTo
method. Basically it calls e1.compareTo(e2)
for elements of the array. This will throw an Exception if either e1
or e2
is null.
Solution: use the 2-parameter Arrays.sort(T[], Comparator<? super t)
and provide a Comparator
that is able to compare 2 elements even if one or both are null.
Very simple example (compares null
as being 0
):
var comparator = Comparator.comparingInt((Integer n) -> n==null ? 0 : n.intValue());
Arrays.sort(arr, comparator);
A class implementing Comparator
can also be used for more complex ordering:
class MyComparator implements Comparator<Integer> {
@Overwrite
public int compare(Integer a, Integer b) {
if (a == null && b == 0) return 0;
if (a == null) return -1;
... // must be implemented
}
}
Arrays.sort(arr, new MyComparator());
no IDE was used or hurt while composing this post; included code is meant only as idea how to solve the problem - it is incomplete, eventually wrong or even contain compilation errors
List<Integer> sortedArray = Arrays.stream(arr)
.filter(x -> x != null)
.sorted().toList();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.