Why are empty collections of different type equal?

后端 未结 2 602
不思量自难忘°
不思量自难忘° 2021-02-11 12:10

What is mechanism below that makes equal different types?

import static org.testng.Assert.assertEquals;
@Test
public void whyThisIsEq         


        
相关标签:
2条回答
  • 2021-02-11 12:56

    They are not...

    System.out.println(new HashSet<>().equals(new ArrayList<>())); // false
    

    This is specific to testng assertEquals

    Looking at the documentation of that method it says:

    Asserts that two collections contain the same elements in the same order.

    And this is ridiculous to me, a Set does not have an order, per-se.

    Set<String> set = new HashSet<>();
    set.add("hello");
    set.add("from");
    set.add("jug");
    
    System.out.println(set); // [from, hello, jug]
    
    IntStream.range(0, 1000).mapToObj(x -> x + "").forEachOrdered(set::add);
    IntStream.range(0, 1000).mapToObj(x -> x + "").forEachOrdered(set::remove);
    
    System.out.println(set); // [jug, hello, from]
    

    So comparing these against a Collection at some particular point in time would yield interesting results.

    Even worse, java-9 Set::of methods implement a randomization internally, so the order (or not the order) will be different from run to run.

    0 讨论(0)
  • 2021-02-11 13:11

    The assertEquals(Collection<?> actual, Collection<?> expected) documentation says:

    Asserts that two collections contain the same elements in the same order. If they do not, an AssertionError is thrown.

    Thus the content of the collections will be compared which, in case both the collections are empty, are equal.

    0 讨论(0)
提交回复
热议问题