简体   繁体   中英

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. 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. 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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