有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何进行lastIndexOf与indexOf的比较?

对于我的java程序,我使用的是SingleLinkedList。下面是我测试的indexOf代码,它运行正常。我的问题是如何将indexOf更改为lastIndexOf。我有点搞不清楚它是怎么工作的,怎么做的

/**
 * Returns the index of the first occurrence of the specified element in this list, or -1 if this list
 * does not contain the element. More formally, returns the lowest index i such that 
 * (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.
 * @param item
 * @return the index of the first occurrence of the specified element in this list, 
 * or -1 if this list does not contain the element
 */
public int indexOf(E item) {

    Node<E> temp = head;
    for(int i=0; i < size; i++){
        if(temp.data.equals(item))
            return i;
        temp = temp.next;
    }
    return -1;

}

以下是lastIndexOf的java文档和标题:

/**
 * Returns the index of the last occurrence of the specified element in this list,
 * or -1 if this list does not contain the element. More formally, returns the highest
 * index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.
 * @param item
 * @return the index of the last occurrence of the specified element in this list, 
 * or -1 if this list does not contain the element
 */
public int lastIndexOf(E item) {
    // TODO Auto-generated method stub
    return 0;
}

共 (1) 个答案

  1. # 1 楼答案

    只需使用一个变量存储找到的最大索引,然后返回:

    /**
     * Returns the index of the last occurrence of the specified element in this list,
     * or -1 if this list does not contain the element. More formally, returns the highest
     * index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.
     * @param item
     * @return the index of the last occurrence of the specified element in this list, 
     * or -1 if this list does not contain the element
     */
    public int lastIndexOf(E item) {
        int index = -1;
        Node<E> temp = head;
        for(int i=0; i < size; i++){
            if(temp.data.equals(item))
                index = i;
            temp = temp.next;
        }
        return index;
    }