Java-如何按顺序查找数组中可能未填充的元素的最后一次出现



我需要编写一个方法,在数组中最后一次出现元素"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;
}

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

你可以用这行:

int whereItIs = Arrays.asList(array).indexOf(item);

最新更新