2013-03-15 75 views
0

我有對象的ArrayList,我試圖在arrayList.getName() == target在對象的列表,你怎麼能得到的對象時,你只能擁有對象的唯一名稱

if(arrayList.contains(target)){ 
    System.out.print(arrayList.get(target)); 
} 
+0

您比較的字符串,然後使用'String.equals()'方法.. – Smit 2013-03-15 18:22:44

+0

那麼,你的問題是什麼? – imulsion 2013-03-15 18:22:47

+0

你的代碼與你的目標有什麼關係? – antonijn 2013-03-15 18:22:56

回答

5

假設你的對象是Foo類型:

for (Foo item : arrayList) { 
    if (item.getName().equals(target)) return item;  
} 
0
返回對象
for (int i = 0; i < arrayList.size(); ++i) { 
    if (arrayList.get(i).equals(target)) 
    return i; 
} 

或更好:

arrayList.indexOf(target) 
0

使用此

arrayList.get(arrayList.indexOf(target)) 

您需要檢查-1條件。

0
if(arrayList.contains(target)){ 
    System.out.print(arrayList.get(arrayList.indexOf(target))); 
} 
+0

因此,如果'target'在這個列表中,爲什麼要使用'get()'和'indexOf()'?。其餘的方法調用是不需要的。 – 2013-03-15 18:28:02

+2

我只是想解決OP的代碼:)你說得對,當涉及到實際行爲時,方法調用是多餘的,但希望它對於get和indexOf的工作方式有一定的學習價值。 – ghdalum 2013-03-15 18:37:30

1

你可以試試這個:

int index = list.indexOf(elementToBeMatched); 
    if (index != -1) { 
     // Match found. Use this index 
    } else { 
     // match not found 
    } 
相關問題