How does an element in Java ignore its own loop and compare whether there are the same elements in the collection

How does an element in Java ignore its own loop and compare whether there are the same elements in the collection


code show as below:

 /**
     * Java 中一个元素在集合中如何忽略自己循环比对是否存在相同元素
     */
    @Test
    public void test02() {
    
    
        // 1. 准备好要比较的集合
        List<Integer> list = new ArrayList<>();
        // 2. 可以看到集合中只有 1002 是重复存在的
        list.add(1001);
        list.add(1002);
        list.add(1003);
        list.add(1005);
        list.add(1005);

        // 3.循环集合做比较
        for (int i = 0; i < list.size(); i++) {
    
    
            // 4. 首先获取到第一个要做比较的对象
            Integer item = list.get(i);
            // 5. 从集合中移除此对象,实现忽略自己做比较
            // 这一步如果没有执行,第一次进来是 1001,然后直接和自己比较,就会进入判断
            list.remove(item);
            for (Integer it : list) {
    
    
                if (it.equals(item)) {
    
    
                    System.err.println("集合中存在相同的元素:[" + item + "]");
                    return;
                }
            }
            // 6. 比较完后再将之前移除的元素添加回来,进行下一轮对比
            list.add(item);
        }
        System.out.println("集合中不存相同元素");
    }

When the same element exists in the
Insert picture description here
set : When the same element does not exist in the set:
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_43647359/article/details/107779013