我在 java.util.ArrayList.containsAll 中发现了一个错误吗? [英] Have I found a bug in java.util.ArrayList.containsAll?

查看:27
本文介绍了我在 java.util.ArrayList.containsAll 中发现了一个错误吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 中,我有两个列表:

In Java I've two lists:

List<Satellite> sats = new ArrayList<Satellite>();
List<Satellite> sats2 = new ArrayList<Satellite>();

Satellite sat1 = new Satellite();
Satellite sat2 = new Satellite();

sats.add(sat1);

sats2.add(sat1);
sats2.add(sat2);

当我在第一个列表中执行以下 containsAll 方法时:

When I do the following containsAll method on the first list:

sats.containsAll(sats2); //Returns TRUE!

它返回真.但是第一个列表 (sats) 仅包含 1 个项目,第二个列表包含 2 个.因此,第一个列表 (sats) 甚至不可能包含第二个列表 (sats2) 中的所有项目.知道为什么或这是 Java JDK 中的错误吗?

It returns true. But the first List (sats) only contains 1 item and the second list contains 2. Therefor it's not even possible that the first list (sats) containsAll items from the second list (sats2). Any idea why or is this a bug in the Java JDK?

我在另一个 StackOverflow 问题中读到,这不是执行此类操作的最高效方法,因此,如果有人对如何提高性能有建议,那就太好了!

I've read in another StackOverflow question that this is not the most performant way to do something like this, so if anyone has a suggestion on how to make it more performant that would be great!

提前致谢!

推荐答案

正如@Progman 所指出的,您可能覆盖了 Satellite 中的 equals 方法.

As pointed out by @Progman, you're probably overriding the equals method in Satellite.

下面的程序打印false.

import java.util.*;

class Satellite {
}

class Test {
    public static void main(String[] args) {
        List<Satellite> sats = new ArrayList<Satellite>();
        List<Satellite> sats2 = new ArrayList<Satellite>();

        Satellite sat1 = new Satellite();
        Satellite sat2 = new Satellite();

        sats.add(sat1);

        sats2.add(sat1);
        sats2.add(sat2);

        System.out.println(sats.containsAll(sats2));
    }
}

(ideone.com 演示)

我建议您打印两个列表的内容并检查内容是否符合您的预期.

I suggest that you print the contents of the two lists and check that the content corresponds to what you expect it to be.

这篇关于我在 java.util.ArrayList.containsAll 中发现了一个错误吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆