2012-06-24 44 views
0

我在調用一個傳入變量的方法。我希望能夠將此變量與ArrayList中的所有項目進行比較,以查看是否有匹配項。我如何比較變量的數據與ArrayList中的數據?

這是我的代碼...

private boolean input; 
private ArrayList chcekItem = new ArrayList(); 

public void setAction(String action) { 
    input=true; 

    if (getChcekItem().isEmpty()) { 
     getChcekItem().add(action); 
    } 
    else {    
     Iterator iterators = getChcekItem().iterator(); 
     while (iterators.hasNext()) {     
      if (iterators.next()==action) { 
       System.out.println(iterators.next()+"="+action); 
       input=false; 
      } 
     }    
     if (input) { 
      getChcekItem().add(action); 
      System.out.println("The item " + action + " is Successfully Added to  array"); 
     } 
     else{ 
      System.out.println("The item " + action + " is Exist"); 
     } 
    } 
} 

如我所預料的我的代碼無法正常工作。有人可以幫我解決這個問題。

回答

3

我認爲checkItem變量是字符串列表,因此應該被定義是這樣的:

private List<String> checkItem = new ArrayList<String>(); 

在比較你不使用字符串1的字符串==字符串2,但string1.equals(字符串2);

所以

(iterators.next()==action) 

應該是:

(iterators.next().equals(action)) 

記住檢查字符串空值。

所以整個代碼看起來是這樣的:

private boolean input; 
private List<String> chcekItem= new ArrayList<String>(); 

public void setAction(String action) { 
input=true; 
if (getChcekItem().isEmpty()) { 
     getChcekItem().add(action); 
    } else { 
     //Foreach loop instead of an iterator ;) 
     for(String item : chcekItem) { 
      if(item.equals(action)) { 
       System.out.println(item+"="+action); 
       input=false; 
       //We can jump out of the loop here since we already found a matching value 
       break; 
      } 
     }   
     if (input) { 
      getChcekItem().add(action); 
      System.out.println("The item " + action + " is Successfully Added to    array"); 
     }else{ 
      System.out.println("The item " + action + " is Exist"); 
     } 
     } 
    } 
}