SetTest refactor (#1724)

This commit is contained in:
Grzegorz Piwowarek 2017-04-27 16:58:13 +02:00 committed by maibin
parent 55dc9a7a9a
commit 2bebf73db2
1 changed files with 28 additions and 23 deletions

View File

@ -1,16 +1,12 @@
package com.baeldung.java.set;
import org.junit.Test;
import java.util.*;
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
@ -44,22 +40,22 @@ public class SetTest {
@Test
public void givenHashSetAndTreeSet_whenAddObjects_thenHashSetIsFaster() {
long hashSetInsertionTime = measureExecution(() -> {
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);
long TreeSetInsertionTime = measureExecution(() -> {
Set<String> set = new TreeSet<>();
set.add("Baeldung");
set.add("is");
set.add("Awesome");
});
assertTrue(hashSetInsertionTime < TreeSetInsertionTime);
}
@Test
@ -86,4 +82,13 @@ public class SetTest {
it.next();
}
}
private static long measureExecution(Runnable task) {
long startTime = System.nanoTime();
task.run();
long endTime = System.nanoTime();
long executionTime = endTime - startTime;
System.out.println(executionTime);
return executionTime;
}
}