Java element comparison performance

Problem:

Given two Collection<?>s, check to see if they contain the same elements.

  • Assuming the actual implementation of the collection is unknown
  • Assuming the elements do not occur in the same order
  • Assuming no items are found twice in the same collection

Solution 1:

boolean equals = c1.containsAll(c2) && c2.containsAll(c1);

Solution 2:

boolean equals = new HashSet<?>(c1).equals(new HashSet<?>(c2));

I would suggest that Solution 2 is more efficient (O (n)) than Solution 1 (O (n ^ 2)).

Will I fix it or miss something?

+4
source share
2 answers

, 1 (O (n)) , O (n^2). 2 O (n) (O (n)) O (1) .contains() . , O (n).

( , ).

  • , .containsAll(). , ( O (n), , O (n^2)), .containsAll().

  • c2 Set, ; c1 .containsAll().

  • instanceof Set , c1 c2 Set, .containsAll(); O (n), , , 2.

+8

dimo414, , . ( , ). :

if (c1.size() != c2.size()) {
    return false;
} else if (c1 instanceof Set) {
    return c1.containsAll(c2);
} else if (c2 instanceof Set) {
    return c2.containsAll(c1);
} else {
    return new HashSet<>(c1).containsAll(c2);
}

size, , , ...

+2

All Articles