1

我需要编写一个方法来查找数组中最后一次出现元素“item”之后的索引。如果找不到项目,我还必须在下一个最大项目之前找到索引。这就是我到目前为止所拥有的。

public int findLast(E item)
    int index = array.length - 1;

    while (index >= 0 && comp.compare(item, array[index]) < 0) {
        index--;
    }

    return index;
}

我相信如果数组中有匹配项,这将找到索引,如果没有找到匹配项,则找到下一个最大值,除非数组未满。如果数组中的某些位置未在数组末尾填充并且仍然为空,则对比较器的调用会给我一个 NullPointerException。我需要能够解决这个问题。任何帮助,将不胜感激!

编辑:这是一些示例输出。这可能没有太大意义,因为这是我需要构建的更大数据结构中的方法的一个非常淡化的版本,称为不规则数组列表。

Exception in thread "main" java.lang.NullPointerException
at java.lang.String.compareTo(Unknown Source)
at RaggedArrayList$StringCmp.compare(RaggedArrayList.java:360)
at RaggedArrayList$StringCmp.compare(RaggedArrayList.java:1)
at RaggedArrayList.findEnd(RaggedArrayList.java:149)
at RaggedArrayList.add(RaggedArrayList.java:170)
at RaggedArrayList.main(RaggedArrayList.java:309)
4

2 回答 2

0

为避免访问未初始化的实例,array[index] == null请在循环条件中添加“OR”,如下所示:

public int findLast(E item)
    int index = array.length - 1;

    while (index >= 0 && (array[index] == null || comp.compare(item, array[index]) < 0)) {
        index--;      //  ^^^^^^^^^^^^^^^^^^^^^^^
    }

    return index;
}

更好的方法是传递已设置数据的数组的最后一个索引。最好的方法是使用动态增长的集合,而不是依赖不能改变大小的数组。

于 2013-10-14T19:00:59.590 回答
0

您可以使用此行:

int whereItIs = Arrays.asList(array).indexOf(item);
于 2013-10-14T18:59:51.480 回答