Java – 获取数组中的元素位置

我熟悉我可以在数组中获取元素位置的方法,尤其是这里显示的元素位置 : 数组中的元素位置

但我的问题是我无法弄清楚如何转换此代码以满足我的需求。

我想要检查的是String是否在ArrayList中匹配,如果是,那么ArrayList中String的索引是什么。

烦人的部分是我设法validationString在ArrayList中(参见我的代码的第一行)

listPackages是ArrayList

current_package是我想在listPackages中找到它的位置的String。

这是我的代码:

if (listPackages.contains(current_package)) { int position = -1; for(int j = 0; j < listPackages.size(); j++) { if(listPackages[j] == current_package) { position = j; break; } } } 

非常感谢任何帮助!

谢谢!

使用indexOf

 int index = listPackages.indexOf(current_package); 

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

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

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

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

希望这会对你有所帮助。像这样改变你的代码:

 if (listPackages.contains(current_package)){ int position=listPackages.indexOf(current_package); } 

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

使用indexof方法获取位置 –

 listPackages.indexOf(current_package) 

http://download.oracle.com/javase/1.4.2/docs/api/java/util/ArrayList.html#indexOf(java.lang.Object