Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are empty collections of different type equal?

What is mechanism below that makes equal different types?

import static org.testng.Assert.assertEquals; 
@Test public void whyThisIsEqual() {     assertEquals(new HashSet<>(), new ArrayList<>()); } 
like image 533
Bartek Avatar asked Sep 06 '18 10:09

Bartek


People also ask

Are two empty lists equal?

When you compare 2 lists with each other, the equals method will NOT compare the items that are in that list. It will just compare the List object with the other List object. these have their own 'identity'.

Are two empty lists equal Java?

Meaning if both lists are empty the last condition is evaluated, which results in true. "Meaning if both lists are empty" Not just if they're empty: if they both contain all null elements (and are the same size), they're also equal.

What is the correct way of returning empty collection?

Collections. emptyList() : method used to return an empty list. Collections. emptySet() : method used to return an empty set.


1 Answers

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.

like image 183
S.K. Avatar answered Sep 22 '22 10:09

S.K.