我需要编写一个方法来查找数组中元素“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)
最佳答案
为了避免访问未初始化的实例,请将 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;
}
更好的方法是传递已设置数据的数组的最后一个索引。最好的方法是使用动态增长的集合,而不是依赖大小无法改变的数组。
关于Java-如何顺序查找数组中可能未填充的元素的最后一次出现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19367119/