Skip to content

Commit

Permalink
HashSet and TreeSet comparison (eugenp#1698)
Browse files Browse the repository at this point in the history
  • Loading branch information
maibin authored and KevinGilmore committed Apr 25, 2017
1 parent 91552e1 commit 4eb3f44
Showing 1 changed file with 89 additions and 0 deletions.
89 changes: 89 additions & 0 deletions core-java/src/test/java/com/baeldung/java/set/SetTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
package com.baeldung.java.set;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.util.ConcurrentModificationException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

import org.junit.Test;

public class SetTest {

@Test
public void givenTreeSet_whenRetrievesObjects_thenNaturalOrder() {
Set<String> set = new TreeSet<>();
set.add("Baeldung");
set.add("is");
set.add("Awesome");
assertEquals(3, set.size());
assertTrue(set.iterator()
.next()
.equals("Awesome"));
}

@Test(expected = NullPointerException.class)
public void givenTreeSet_whenAddNullObject_thenNullPointer() {
Set<String> set = new TreeSet<>();
set.add("Baeldung");
set.add("is");
set.add(null);
}

@Test
public void givenHashSet_whenAddNullObject_thenOK() {
Set<String> set = new HashSet<>();
set.add("Baeldung");
set.add("is");
set.add(null);
assertEquals(3, set.size());
}

@Test
public void givenHashSetAndTreeSet_whenAddObjects_thenHashSetIsFaster() {
Set<String> set = new HashSet<>();
long startTime = System.nanoTime();
set.add("Baeldung");
set.add("is");
set.add("Awesome");
long endTime = System.nanoTime();
long duration1 = (endTime - startTime);

Set<String> set2 = new TreeSet<>();
startTime = System.nanoTime();
set2.add("Baeldung");
set2.add("is");
set2.add("Awesome");
endTime = System.nanoTime();
long duration2 = (endTime - startTime);
assertTrue(duration1 < duration2);
}

@Test
public void givenHashSetAndTreeSet_whenAddDuplicates_thenOnlyUnique() {
Set<String> set = new HashSet<>();
set.add("Baeldung");
set.add("Baeldung");
assertTrue(set.size() == 1);

Set<String> set2 = new TreeSet<>();
set2.add("Baeldung");
set2.add("Baeldung");
assertTrue(set2.size() == 1);
}

@Test(expected = ConcurrentModificationException.class)
public void givenHashSet_whenModifyWhenIterator_thenFailFast() {
Set<String> set = new HashSet<>();
set.add("Baeldung");
Iterator<String> it = set.iterator();

while (it.hasNext()) {
set.add("Awesome");
it.next();
}
}
}

0 comments on commit 4eb3f44

Please sign in to comment.