与indexOf相比,lastIndexOf如何做?

时间:2014-03-10 03:45:37

标签: java javadoc

对于我的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 doc和header:

/**
 * 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 个答案:

答案 0 :(得分:0)

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

/**
 * 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;
}