简体   繁体   中英

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?

That is because the array is filled with null pointers. The comparator can't compare the null objects with each other.

Creating an array doesn't initialise each element of the array.

Make sure to have only non-null elements in your array regarding your implementation of compareTo(). Otherwise, in your function compareTo(), calling "q" attribute on a supposed existing judgement causes a NullPointerException.

Furthermore, avoid tabs, prefer using Collections. In your case, you can use TreeSet objects instead of arrays since they internally use compareTo() method of elements into them.

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

What's probably happening is that some elements of your array are null .

It's good practice to include a null check in your compareTo function. Also, right now your compareTo function is non-functional: it always returns 0 -- this is like saying that all items are equal.

Your other problem is that it looks like you're using a try{}finally{} for things that it shouldn't be used for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM