有 Java 编程相关的问题?

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

java生成一个定制的lastIndexOf方法

int found = 0;
int index = 0;
while (index < list.size()) {
    if(list.get(index) == z) {
        found = index;
    }
    index++;
}
return found;

z只是对象的名称 我试图弄明白为什么在arraylist中查找lastIndexOf而不使用已经内置到java中的lastIndexOf方法是错误的

有人能指出我的错误方向吗


共 (2) 个答案

  1. # 1 楼答案

    首先,您希望使用equals,而不是将引用与==进行比较

    其次,您希望found的初始值为-1,以防在列表中找不到元素(否则,当找不到元素时,将返回0,这是一个有效的索引)

    int found=-1;
    int index=0;
    while (index<list.size()){
        if(list.get(index).equals(z)){
            found=index;
        }
        index++;
    }
    return found;
    

    当然,从列表末尾向后迭代会更有效

    int index=list.size() - 1;
    while (index >= 0){
        if(list.get(index).equals(z)){
            return index;
        }
        index ;
    }
    return -1;
    
  2. # 2 楼答案

    三个问题:

    1)如果未找到元素,则应返回不是容器有效索引的索引。让我们使用-1,尽管JavaBOD可能比这做得更好,比如返回一个负值,该负值与元素在容器中的位置有关

    2)你需要从列表的末尾开始,并向后工作。否则你不一定能找到最后一个

    3)不要使用==来比较值。改用equals

    把这些放在一起,去掉一个冗余变量,就可以

    int index;
    for (index = list == null ? -1 : list.size() - 1; index >= 0;  index){
        if (list.get(index).equals(z)){
            break;
        }
    }
    return index;
    

    遍历容器可能有更好的方法:我无意中为随机查找为O(N)的容器构建了一个O(N*N)算法,但这应该让您开始