2011-09-28 123 views
14

元素位置我熟悉的方式,我可以得到在數組中的元素的位置,特別是那些表明這裏: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對象,甚至是字符串。始終使用等號方法。 –

+0

謝謝,你是對的...複製粘貼:) –

回答

36

使用indexOf

int index = listPackages.indexOf(current_package); 

請注意,您應該不一般使用==比較字符串 - 將比較引用,即兩個值是否是,同一個對象的引用,而不是等於字符串。相反,您應該撥打equals()。這可能是你現有的代碼出錯了,但顯然使用indexOf要簡單得多。

+0

+1和感謝的誠實的錯誤,你的回答讓我 –

3

只使用通話listPackages.indexOf(current_package);

ArrayList.contains(Object o)電話indexOf(Object o)在內部的ArrayList:

/** 
* 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; 
} 
1

合Ë這將幫助你you.change這樣的代碼:

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

此外,如果你將位置變量作爲全球你可以的代碼塊外部訪問它的價值。 :)

+0

作品,但沒有必要遍歷列表的兩倍。只需使用indexOf。如果ArrayList中不包含字符串則返回-1 – Steve

+0

是的,你是什麼right.But如果ArrayList中亙古不變的包含字符串,你會嘗試找到它的indexOf.Will有任何例外呢?我想是這樣的,但我有沒有嘗試過這種類型。 –

+0

也不例外,它會返回-1 – Steve