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]);
}
}
}