Java - 获取数组元素的位置

21

我知道几种可以获取数组元素位置的方法,尤其是这里展示的方法:Element position in array

但我的问题是我不知道如何将这个代码转换以适应我的需求。

我想要检查的是一个字符串在ArrayList中是否有匹配项,如果有,那么这个字符串在ArrayList中的索引是什么。

让人恼火的是,我已经成功验证了该字符串是否在ArrayList中(请参见代码的第一行)。

listPackages是ArrayList

current_package是我要在listPackages中找到其位置的字符串。

以下是我的代码:

if (listPackages.contains(current_package)) {

        int position = -1;
        for(int j = 0; j < listPackages.size(); j++) {

            if(listPackages[j] == current_package) {
              position = j;
                  break;
              }
            }
    }

非常感谢任何帮助!

谢谢!


1
同样,在Java中比较对象甚至字符串时,请不要使用“==”运算符,而应该始终使用equals方法。 - mateusz.fiolka
谢谢,你说得对...复制粘贴时的诚实错误 :) - Lior Iluz
4个回答

44

使用 indexOf 方法:

int index = listPackages.indexOf(current_package);

请注意,通常不应使用==来比较字符串 - 这将比较引用,即两个值是否引用相同的对象,而不是相等的字符串。相反,应该调用equals()。这可能是您现有代码出错的原因,但显然使用indexOf要简单得多。


3

只需使用调用listPackages.indexOf(current_package);

ArrayList.contains(Object o)在ArrayList内部调用indexOf(Object o)

/**
 * Returns <tt>true</tt> if this list contains the specified element.
 * More formally, returns <tt>true</tt> if and only if this list contains
 * at least one element <tt>e</tt> such that
 * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
 *
 * @param o element whose presence in this list is to be tested
 * @return <tt>true</tt> if this list contains the specified element
 */
public boolean contains(Object o) {
return indexOf(o) >= 0;
}

2
希望这能帮到你。请将代码更改为以下内容:
if (listPackages.contains(current_package)){
int position=listPackages.indexOf(current_package);
}

此外,如果您将位置变量设置为全局变量,则可以在此代码块之外访问其值。 :)

可以使用indexOf方法,而不需要遍历列表两次。如果ArrayList不包含该字符串,则此方法将返回-1。 - Steve
没错,但是如果那个 ArrayList 不包含一个字符串并且你尝试寻找它的索引,会发生异常吗?我猜可能会,但我还没有尝试过这种情况。 - Android Killer

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接