我找到在java.util.ArrayList.containsAll的错误吗? [英] Have I found a bug in java.util.ArrayList.containsAll?

查看:142
本文介绍了我找到在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!

返回TRUE。但第一个List(SATS)只包含1项和第二个列表包含2为此它甚至有可能是从第二个列表(sats2)第一个列表(SATS)containsAll项目。任何想法,为什么还是这在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?

我读过在另一个计算器疑问,这是不是这样做最高效的方式,因此,如果任何人有如何使它更好的性能,这将是伟大的一个建议!

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指出的那样,你可能重写等于<$ C $ 方法C>卫星。

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

下面打印程序

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天全站免登陆