Why are empty collections of different type equal?

后端 未结 2 635
不思量自难忘°
不思量自难忘° 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 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.

提交回复
热议问题