Have I found a bug in java.util.ArrayList.containsAll?

℡╲_俬逩灬. 提交于 2019-12-25 07:58:51

问题


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);

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

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

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!

Thanks in advance!


回答1:


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

The program below prints 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 demo)

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




回答2:


For many classes, it makes sense that two objects created the same way (e.g. new Satellite()) would be considered equal. Keep in mind that containsAll doesn't care about the number of copies of an object that a Collection contains, just that it contains at least one of each distinct element in the Collection that it's given. So for example, if you had a List a that contained [A, A] and a list b that just contained [A], b.containsAll(a) and a.containsAll(b) would both return true. This is probably analogous to what's happening here.




回答3:


Too late to reply but the second part of your question - a more efficient way to do containsAll is : CollectionUtils.isSubCollection(subSet, superSet) That is O(n^2) vs O(n) complexity



来源:https://stackoverflow.com/questions/5708445/have-i-found-a-bug-in-java-util-arraylist-containsall

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!