[英]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;
我看不到您在哪里使用size
和rear
但您可能也希望它们是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.