简体   繁体   English

Java对象比较

[英]Java object compareto

private Comparable[] items = new Comparable[1000000];   

bubbleSort(items);

public static <T extends Comparable<T>> void bubbleSort(T[] list){

    T temp;
    for (int k = 1; k < list.length; k++) {
    // Perform the kth pass
        for (int i = 0; i < list.length - k; i++) {
            if (list[i].compareTo(list[i + 1]) > 0){
                temp = list[i];
                list[i] = list[i + 1];
                list[i + 1] = temp;
            }
        }
    }
}

The problem I'm having is with if (list[i].compareTo(list[i]) > 0) . 我遇到的问题是if (list[i].compareTo(list[i]) > 0) I've commented everything out, one line at a time. 我已经注释掉了所有内容,一次一行。 That is the only thing that causes the error, and it doesn't give me any explanation in the output. 那是导致错误的唯一原因,并且在输出中也没有给我任何解释。 Just which lines it is. 到底是哪几行。 which would be at the if, and calling the bubbleSort method. 它将位于if处,并调用bubbleSort方法。

private Comparable[] items = new Comparable[1000000];  

This line does not initialize any element in the array. 该行不初始化数组中的任何元素。 You have null in every slot, hence your NullPointerException . 每个插槽中都为null ,因此为NullPointerException

Or maybe you just didn't post init code, but then the problem would be there. 也许您只是没有发布初始化代码,但是问题就在那里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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