簡體   English   中英

CompareTo方法中的空指針異常

[英]Null pointer Exception in CompareTo method

我班的結構:

public class Priorityy implement Comparable {
    public int compareTo(Object pe) {
        Priorityy p = (Priorityy) pe;
        if (this.key < p.key) {    
            return 1;
        } else if (this.key > p.key) {
            return -1;
        } else {
            return 0;
        }
    }
}

問題是p.key始終為null,這到底是為什么? 我已經用數組中的元素初始化了數組,但是每當我嘗試Arrays.sort(arr)時,它總是拋出NullPointerException。

我怎樣才能解決這個問題?

編輯:這是完整的代碼,並且print確實打印了數組arr的元素:

import java.util.Arrays;

class Priorityy implements Comparable {
    int size;
    int front = 0;
    int rear = 0;
    static Priorityy[] arr = new Priorityy[3];
    int key;
    String value;

    public Priorityy(int key, String value) {
        this.key = key;
        this.value = value;
        insert();
    }

    public void insert() {
        arr[front] = this;
        System.out.println(arr[front].value);
        while (front + 1 != 3) {
            front = front + 1;
        }
    }

    public Priorityy remove() {
        Priorityy x = arr[front];
        front = front - 1;
        return x;
    }

    public int compareTo(Object pe) {
        Priorityy p = (Priorityy) pe;
        if (this.key < p.key) {
            System.out.println(p.key);

            return 1;
        } else if (this.key > p.key) {

            System.out.println("3");
            return -1;
        } else {
            System.out.println("4");
            return 0;
        }
    }

    public static void main(String... s) {
        new Priorityy(10, "Watch");
        new Priorityy(40, "Laptop");
        new Priorityy(60, "Wallet");
        Arrays.sort(arr);
        for (Priorityy element : arr) {
            System.out.println(element.key);
            System.out.println(element.value);
        }
    }
}

您以一種非常奇怪的方式將事物放入數組中。 但考慮到,問題是,你不能使用static字段來存儲下一個位置插入一個元素,所以你創建的實例下一次Priorityy ,本場first值為零一次。 因此,您要將所有三個對象插入數組的元素零。

更改一行代碼即可使用:

int front = 0;

至:

static int front = 0;

我看不到您在哪里使用sizerear但您可能也希望它們是static

另一個建議:Java有一個很好的簡短語法,可以使用++或-運算符將變量的值增加或減少一個,因此您可以通過以下方式縮短代碼長度:

front++;

代替

front = front + 1;

(and front--而不是front = front - 1

根據您的代碼

Priorityy p = (Priorityy)pe;
                         ^^ ---------- this is null

數組中null對象。 優雅地處理null對象。

例如

if(pe instanceof Priorityy){ // return false for null object
     // your code goes here
}

最好使用Generic Comparable並使用Integer.compare(int,int)比較兩個int值。

class Priorityy implements Comparable<Priorityy> {
    public int compareTo(Priorityy pe) {
        if (pe != null) {
            return Integer.compare(this.key, pe.key);
        } else {
            // return what ever if pe is null
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM