Java “无法读取字段”;“价值”;因为";另一个字节“;是空的
这里我有一个快速排序算法。基类具有函数isLessThan() 是什么导致了这个错误 我的主要观点如下:Java “无法读取字段”;“价值”;因为";另一个字节“;是空的,java,comparable,Java,Comparable,这里我有一个快速排序算法。基类具有函数isLessThan() 是什么导致了这个错误 我的主要观点如下: public class Main { public static void main(String[] args) { Byte[] array = {121, 25, 44, 17, 30, 55, 29, 7, 81, 45, 79, 41, 108, 60, 83, 29, 77, 5, 17, 110}; Quick s = new Qu
public class Main {
public static void main(String[] args) {
Byte[] array = {121, 25, 44, 17, 30, 55, 29, 7, 81, 45, 79, 41, 108, 60, 83, 29, 77, 5, 17, 110};
Quick s = new Quick();
s.sort(array);
}
}
您的假设此代码的其余部分可能与我的问题无关是错误的。因为它是low[0]
,实际上是null
// the rest of this code probably isn't relevant to my problem
// sort low, then high
if (lowCount > 1) {
System.out.println("LOW: " + low[0]);
low = processPartition(low, low[0]);
}
if (highCount > 1) {
System.out.println("HIGH: " + high[0]);
high = processPartition(high, high[0]);
}
您实例化这两个数组,并说它们与原始数组具有相同的维度。这没关系
low = (T[]) new Comparable[arr.length];
high = (T[]) new Comparable[arr.length];
但你的错误是,你使用了错误的索引方法!从for循环中获取索引,并将其作为索引传递给数组
for (int i = 0; i < arr.length; i++) {
if (arr[i] != null) {
if (isLessThan(arr[i], partition)) {
addLow(arr[i], i);
lowCount++;
} else {
addHigh(arr[i], i);
highCount++;
}
}
for(int i=0;i
但是会发生什么呢
在第一次比较中,121对121。这不小于但等于。如果大于或等于,则进入else部分并调用addHigh()
因此,指数0已达到高位
现在比较还在继续,其他的都是LessThan()
,因为121是列表中的最高数字
但是,当您从循环中输入索引时,第一个LessThan()值不会进入low[0]
,而是low[1]
low[0]
为null
然后您稍后调用low=processPartition(low,low[0]);
并获取您的NPE
所以你至少有一件事要做:
不要在for循环外使用索引i
!那是错误的
请使用您的计数器lowCount
和highCount
!它们将始终指向数组中的正确字段
请注意,这只会解释为什么您在这里得到第一个NPE,并帮助您解决它
当您运行此代码时,会出现相同的NPE消息,但会在过程中的另一个点出现。这一次,因为您总是传递数组并不断更改它们。当代码返回到第一轮并继续运行时,它会找到highCount>1
并尝试处理high[]
-array。但在此期间,此值已更改,高[0]
为空
你必须重新考虑你的整个排序方法
我希望这至少有助于找出一开始出现的问题。您也可以共享您的主类吗?@user1485864已编辑以显示我调用sort()的位置是的,但是你的数组是如何启动的?它包含什么?理想情况下,我们需要一个自包含的示例来重现错误。注意。编辑并测试以重新创建错误。你是对的,解决了这个问题。你也是对的,我的代码仍然无法工作:)哦,好吧。回到绘图板上!
// the rest of this code probably isn't relevant to my problem
// sort low, then high
if (lowCount > 1) {
System.out.println("LOW: " + low[0]);
low = processPartition(low, low[0]);
}
if (highCount > 1) {
System.out.println("HIGH: " + high[0]);
high = processPartition(high, high[0]);
}
low = (T[]) new Comparable[arr.length];
high = (T[]) new Comparable[arr.length];
for (int i = 0; i < arr.length; i++) {
if (arr[i] != null) {
if (isLessThan(arr[i], partition)) {
addLow(arr[i], i);
lowCount++;
} else {
addHigh(arr[i], i);
highCount++;
}
}