java - 如何将变量的数据与 ArrayList 中的数据进行比较?

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

我的代码没有按我的预期运行。有人可以帮我解决这个问题吗?

最佳答案

我认为 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");
        }
      }
    }
}

关于java - 如何将变量的数据与 ArrayList 中的数据进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11176163/

相关文章:

java - 在 ArrayList 中插入不同的数组

java - 错误领域=插件>com.sun.jersey.contribs :maven-wadl-plugin:1. 17

java - 与 Java 同步异步 API 调用

java - 使用 ArrayList 将顶点添加到图形中

python - 在Python中获取列表的每个子列表的第一项

java - 引用数组列表中的值对,然后比较它们

java - ArrayList 充满了随机数,奇怪地导致 foreach 从随机索引中提取

java - Canvas 绘制速度太慢

java - 迁移ehcache :proxy to spring 4

java - 在内存中存储大量 IP 地址