簡體   English   中英

如何將變量的數據與ArrayList中的數據進行比較?

[英]How do i compare a variable's data with the data in an 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");
        }
    }
}

我的代碼無法正常運行。 有人可以幫我解決問題。

我認為checkItem變量是一個字符串列表,因此應該這樣定義:

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

比較字符串時,不使用string1 == string2,而是使用string1.equals(string2);

所以

(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");
        }
      }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM