简体   繁体   English

Java-我如何依次查找可能未填充的数组中元素的最后出现?

[英]Java-How do I sequentially find the last occurrence of an element in an array that may not be filled?

I need to write a method that finds the index after the last occurrence of an element "item" in an array. 我需要编写一个在数组中元素“ item”的最后一次出现之后找到索引的方法。 I also have to find the index before the next largest item if item is not found. 如果没有找到项目,我还必须在下一个最大项目之前找到索引。 This is what I have so far. 到目前为止,这就是我所拥有的。

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

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

    return index;
}

I believe that this will find the index if there is a match within the array, and the next largest value if a match is not found, unless the array is not full. 我相信,如果数组中有匹配项,它将找到索引;如果找不到匹配项,则将找到下一个最大值,除非数组未满。 If some positions in the array are not filled at the end of the array and still null, the call to the comparator gives me a NullPointerException. 如果数组中的某些位置未在数组末尾填充并且仍然为null,则对比较器的调用会给我NullPointerException。 I need to be able to work around that. 我需要能够解决该问题。 Any help would be appreciated! 任何帮助,将不胜感激!

EDIT: Here is some sample output. 编辑:这是一些示例输出。 It may not make too much sense as this is a very watered down version of a method in a larger data structure that I need to build called a ragged arraylist. 这可能没有太大意义,因为这是我需要构建的,称为“参差不齐的数组列表”的较大数据结构中方法的精简版本。

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)

您可以在此行中使用:

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

To avoid accessing an uninitialized instance, add an "OR" with array[index] == null to your loop condition, like this: 为了避免访问未初始化的实例,请在循环条件中添加一个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;
}

A better approach would be passing the last index of the array where the data has been set. 更好的方法是传递已设置数据的数组的最后一个索引。 The best approach would be using collections that grow dynamically, rather than relying on arrays that cannot change in size. 最好的方法是使用动态增长的集合,而不是依赖大小无法更改的数组。

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

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