Java使用数组查找重复项(包含概念)

标签 java list for-loop contains

我正在尝试解决有关如何查找重复数组列表的问题之一。
该程序的工作原理:

import java.util.*;

public class CheckDuplicates {
public static void main(String[]args){

    boolean containsDuplicate;
    int[] values = {1,2,3,4,5,6,7,8,9,1,3,4,5,10};

    List<Integer> myObj = new ArrayList<Integer>();
    Set<Integer> dupInt = new HashSet<Integer>();

    for(int id : values){
        System.out.println(myObj);
        if(myObj.contains(id)){    
            System.out.println("From contains "+id);
            containsDuplicate = true;
            dupInt.add(id);
        }else{
            System.out.println("not contains "+id);
            myObj.add(id);
        }
    }

    for(int dup : dupInt)
        System.out.println(dup); // prints the duplicates
}
}

但是我有一个关于 for 循环部分的概念问题。如果

    List<Integer> myObj = new ArrayList<Integer>();

创建一个空的数组列表,那么这些行是如何工作的?

 for(int id : values){ if(myObj.contains(id)){ // Why is this true?

虽然文档说 包含

boolean contains
(Object o) Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).

Specified by: contains in interface Collection

Parameters: o - element whose presence in this list is to be tested

Returns: true if this list contains the specified element

但是我还是不明白这个概念!预先感谢您的解释。

最佳答案

你是对的,myObj.contains(id)的第一次检查总是错误的,但是看看你代码的其他部分:

else{
        System.out.println("not contains "+id);
        myObj.add(id);
    }

随着循环的进行,您的列表将被填充 - 并且进一步的迭代可能会满足该条件。

关于Java使用数组查找重复项(包含概念),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13409728/

相关文章:

java - Maven XML 插件 - 如何使用 document() 函数定义 URIResolver 或 SystemID 进行转换?

java - ElasticSearch 服务无法在 Windows 上启动

python - 根据分隔符拆分列表

c++ - 在 for 循环中,条件中使用的变量是在每次迭代时检查,还是仅在第一次迭代时检查?

php - 从 PHP Post 使用 PDO 执行多个 MySQL 查询

python - DBSCAN 轮廓系数 : does this for-loop work?

java - Android Studio 和 java 编译器没有 SDK 常量

java - FlowPane 中的可变大小数组

java - 如何列出 put 方法中的参数?

python - 字典列表,按列表键无交集