Search code examples
javasortingnullpointerexceptioncompareto

Java error: java.lang.NullPointerException


I'm writing a code to read some records from a file and sort them in a special manner. I tried a code like this:

public class Main {

    static class judgement implements Comparable<judgement> {
        public int q;
        public int d;
        public int r;

        public int compareTo(judgement j) {
            int k = ((judgement) j).q;
            return 0;
        }
    }

    public static void method() throws Exception {
        judgement[] judgements;
        judgements = new judgement[18425];
        try {
            // fill the "judgements" array
        } finally {
            Arrays.sort(judgements);
        }
    }

    public static void main(String[] args) throws Exception {
        method();
    }

}

But I get the error NullPointerException in the function compareTo. Can anybody help me with this problem?


Solution

  • You are initializing arrays with null values.

    judgements = new judgement[18425];
    

    And you are not checking the null Values in compare to. you have to use if statement.

    public int compareTo(judgement j) {
              int k =0;
        if(j!=null){
        k = ((judgement) j).q;
        } 
    
                    return 0;
                }