Arrays.sort() NullPointerException

Arrays.sort(), compareTo NullPointerException

Are you getting NullPointerException while using Arrays.sort() and Comparable and don’t know exactly where is the problem in your code ?

Solution

You may get this exception when you miss any element or something is null. Check the following example, in this case the array maximum size is 5, but we had inserted only 4 elements and missing 5th element. So it’s throwing a NullPointerException in compareTo.

Arrays.sort() NullPointerException example

Output NullPointerException while usilg Arrays.sort()

If the above error happens while sorting the array, just take a look at how you assign values to array. In the above code either change the Item Array max size from 5 to 4 or insert the missing element to get the following output.

Recommended Posts

References