爪哇 - 获得数组元素的位置 [英] Java - get element position in array

查看:133
本文介绍了爪哇 - 获得数组元素的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我熟悉的方式,我可以得到在数组中的元素的位置,特别是那些显示此处的在数组元素的位置

I'm familiar with the ways I can get an element position in array, especially the ones showed here: Element position in array

但我的问题是我无法弄清楚如何转换这种code适合我的需要。

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中(见我的code的第一行)

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.

下面是我的code:

if (listPackages.contains(current_package)) {

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

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

请问AP preciate任何帮助!

Would appreciate any help!

谢谢!

推荐答案

使用<一个href=\"http://download.oracle.com/javase/6/docs/api/java/util/List.html#indexOf%28java.lang.Object%29\"><$c$c>indexOf:

int index = listPackages.indexOf(current_package);

请注意,你不应该一般使用 == 比较字符串 - 这将比较的引用的,即两个值是否为引用相同的对象,而不是等于串。相反,你应该叫等于()。这可能与您现有的code发生了什么事情错了,但很明显,使用的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.

这篇关于爪哇 - 获得数组元素的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆