0

変数を渡すメソッドを呼び出しています。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");
        }
    }
}

コードが期待どおりに機能していません。誰かが私が問題を解決するのを手伝ってくれませんか。

4

1 に答える 1

3

checkItem変数は文字列のリストであると考えているため、次のように定義する必要があります。

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

文字列を比較するときは、string1 == string2ではなくstring1.equals(string2);を使用します。

それで

(iterators.next()==action) 

する必要があります:

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

文字列のnull値を確認することを忘れないでください。

したがって、コード全体は次のようになります。

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");
        }
      }
    }
}
于 2012-06-24T09:06:23.613 に答える