Java - 获取数组中的元素位置 [英] Java - get element position in array
问题描述
我熟悉获取数组中元素位置的方法,尤其是此处显示的方法:数组中的元素位置
I'm familiar with the ways I can get an element position in array, especially the ones showed here: Element position in array
但我的问题是我不知道如何转换此代码以满足我的需要.
But my problem is I can't figure out how to convert this code to fit my needs.
我想检查一个字符串是否在 ArrayList 中匹配,如果匹配,则该字符串在 ArrayList 中的索引是多少.
What I want to check is if a String has a match in an ArrayList and if so, what's the index of the String in the ArrayList.
烦人的部分是我设法验证字符串是否在 ArrayList 中(请参阅我的代码的第一行)
The annoying part is I managed to verify the String is in the ArrayList (see first line of my code)
listPackages 是 ArrayList
listPackages is the ArrayList
current_package 是我想在 listPackages 中找到它的位置的字符串.
current_package is the String I want to find its position in 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;
}
}
}
非常感谢您的帮助!
谢谢!
推荐答案
使用 indexOf
:
int index = listPackages.indexOf(current_package);
请注意,您通常不应该使用 ==
来比较字符串 - 这将比较 references,即两个值是否是对同一对象的引用,而不是到相等的字符串.相反,您应该调用 equals()
.这可能是您现有代码的问题所在,但显然使用 indexOf
简单得多.
Note that you shouldn't generally use ==
to compare strings - that will compare references, i.e. whether the two values are references to the same object, rather than to equal strings. Instead, you should call equals()
. That's probably what was going wrong with your existing code, but obviously using indexOf
is a lot simpler.
这篇关于Java - 获取数组中的元素位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!