Ayushi bhardwaj Ayushi bhardwaj - 12 days ago 6
Java Question

Exception in thread "main" java.lang.NullPointerException at java.lang.Integer.compareTo(Integer.java:1216)

I am writing java code for sorting an Integer array using my own custom Comparator, the code I written has a block :

Arrays.sort(arrI, new Comparator<Integer>()
{

@Override
public int compare(Integer o1, Integer o2) {

return o2.compareTo(o1);
}
});


Where I'm getting a NullPointerException at this line :

return o2.compareTo(o1);


The reason is perhaps in the method where I'm taking the arguments are just the reference variables (they haven't been initialized with the object value). But knowing that I can't do anything. I'm simply over riding the method which I don't know how and when it is called. So I can't actually solve this problem.

How can I remove the exception?

My complete code is:

import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
import java.util.*;

public class Prob1 {

public static void main(String []args)
{
int arr[] = new int[10+5];
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
for (int i = 0; i < n; ++i)
{
arr[i] = scanner.nextInt();
}
Integer arrI[] = new Integer[arr.length];
int i = 0;
for(int value = 0; value < n; ++value)
{
arrI[value] = Integer.valueOf(arr[value]);
}
Arrays.sort(arrI, new Comparator<Integer>()
{
@Override
public int compare(Integer o1, Integer o2) {

return o2.compareTo(o1);
}
});
for (int k = 0; k < arrI.length; ++k)
{
System.out.println(arrI[k]);
}
}

}

Answer

arr[] has length of 15 and later if user enter n as 10 so your arr will have 10 elements (last five as 0)and so Integer arrI[] = new Integer[arr.length]; will have 15 elements where last 5 will be null so do this

 Integer arrI[] = new Integer[n];

Initializing arr with 15 length seems like isn't the requirement of your code logic so you can simply avoid this by using n at first place to

    int arr[];
    Scanner scanner = new Scanner(System.in);
    int n = scanner.nextInt();
    arr = new int[n]
    .
    .
    Integer arrI[] = new Integer[n]; 
Comments