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
package com.sneppets.dsalgo; import java.util.Arrays; class Item implements Comparable<Item>{ private String itemName; private int price; public Item(String itemName, int price){ this.setItemName(itemName); this.setPrice(price); } @Override public int compareTo(Item compareItem) { int comparePrice = ((Item) compareItem).getPrice(); return this.price - comparePrice; } public String getItemName() { return itemName; } public void setItemName(String itemName) { this.itemName = itemName; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public void printItemDetails() { System.out.print("Item Name: " + itemName + ", "); System.out.println("Price: " + price); } } public class ArraySortNullPointerExceptionExample { public static void main(String[] args) { Item[] itemArray = new Item[5]; Item item1 = new Item("Cofee", 10); Item item2 = new Item("Water", 5); Item item3 = new Item("Milk", 8); Item item4 = new Item("Juice", 20); itemArray[0] = item1; itemArray[1] = item2; itemArray[2] = item3; itemArray[3] = item4; System.out.println("Before Sorting"); printItemArray(itemArray); System.out.println("After Sorting"); Arrays.sort(itemArray); printItemArray(itemArray); } private static void printItemArray(Item[] itemArray) { for (int i=0; i<itemArray.length; i++) { itemArray[i].printItemDetails(); } } }
Output NullPointerException while usilg Arrays.sort()
Before Sorting Item Name: Cofee, Price: 10 Item Name: Water, Price: 5 Item Name: Milk, Price: 8 Item Name: Juice, Price: 20 Exception in thread "main" java.lang.NullPointerException at com.sneppets.dsalgo.ArraySortNullPointerExceptionExample.printItemArray(ArraySortNullPointerExceptionExample.java:74) at com.sneppets.dsalgo.ArraySortNullPointerExceptionExample.main(ArraySortNullPointerExceptionExample.java:63)
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.
Before Sorting Item Name: Cofee, Price: 10 Item Name: Water, Price: 5 Item Name: Milk, Price: 8 Item Name: Juice, Price: 20 After Sorting Item Name: Water, Price: 5 Item Name: Milk, Price: 8 Item Name: Cofee, Price: 10 Item Name: Juice, Price: 20
Recommended Posts
- Sort Java Objects using Insertion Sort
- Insertion Sort Complexity Analysis
- Selection Sort Complexity Analysis
- What are the ways to print arrays in Java ?