有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何将变量的数据与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");
        }
    }
}

我的代码没有像我预期的那样工作。有人能帮我解决这个问题吗


共 (1) 个答案

  1. # 1 楼答案

    我认为checkItem变量是一个字符串列表,因此应该这样定义:

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

    比较字符串时,不使用string1==string2,而是使用string1。等于(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");
            }
          }
        }
    }