java - 如何在运行时检查数组是否包含特定值

标签 java arrays unique

下面提供的代码执行一项任务,即获取所有 xy 或类似字符串,并将其添加到数组中。

我可以将它们全部添加到数组中,但我想要的是检查我要插入数组中的变量是否已经存在,然后不要插入其他插入。

ArrayList vars = new ArrayList();
for(int i = 0; i < temp.length; i++)
    for(int j = 1; j < temp[0].length - 1; j++)
    {
        String text_to_parse = temp[i][j];
        Pattern y = Pattern.compile("[?]\\w[,)]"); // find the values in pattern of ?x, or ?x)
        Matcher z = y.matcher(text_to_parse);
        while(z.find())
        {
            String to_add = z.group();
            to_add = to_add.replaceAll("[\\,\\) ]","");
            // logic required here if to_add exist in vars then do no insert else insert

        }
     }

我尝试使用vars.contain,但它添加了它找到的所有值。

最佳答案

如果 vars 不包含,请尝试。像这样使用 ! 运算符

if (!(vars.contains(item)))
   //add the item
else
   //do nothing

关于java - 如何在运行时检查数组是否包含特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37314343/

相关文章:

java - 打印 Unicode 字符 Android TextView

arrays - 如何在 Go 中将错误数组转换为 JSON

php - 选择唯一的产品 ID 并按库存 ID desc 订购

performance - 如果假设 1d 预排序向量,在 matlab 中实现 unique() 的更快方法?

java - 如何使用 Jsoup 提取 HTML 的单独部分?

Javafx 按钮向 ActionEvent 函数发送参数

java - 与 Java 7 相比,Java 8 中的 GC 明显变慢

arrays - 使用 NodeJS 删除 JavaScript 中的 websocket 连接

c++ - 将 char 数组分配给单个 char 的奇怪行为

java - JSON键是否需要唯一?