简体   繁体   中英

Java Collision in Hashset collection

How I can prove by jUnit test that HashSet handled collision. For example I can fill HashSet with 10000 elements in for loop, but which parameter should show me that I have collision, I suppose to think about collection size, but not pretty sure about it.

If you want to assert that HashSet handles collision of equal values, put in 2 equal values, and assert that only one item is in the set after:

HashSet<String> set = new HashSet<>(Arrays.asList("A", "A"));
assertEquals(1, set.size());

If you want to assert that HashSet handles collision of equal hash codes , put in unequal values with the same hash code, and assert that there are two items in the set after:

assertEquals("Aa".hashCode(), "BB".hashCode());
HashSet<String> set = new HashSet<>(Arrays.asList("Aa", "BB"));
assertEquals(2, set.size());

I don't understand what is the purpose of this test, but you can do it like this:

Set<String> mySet = new HashSet<>();
int numberOfRandomElements = 10000;

mySet.addAll(createRandomElements(numberOfRandomElements));

int diff = numberOfRandomElements - mySet.size();
System.out.println(String.format("Number of elements removed: %d", diff));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM