Skip to content

Commit 2bebf73

Browse files
pivovaritmaibin
authored andcommitted
SetTest refactor (eugenp#1724)
1 parent 55dc9a7 commit 2bebf73

1 file changed

Lines changed: 28 additions & 23 deletions

File tree

‎core-java/src/test/java/com/baeldung/java/set/SetTest.java‎

Lines changed: 28 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,11 @@
11
package com.baeldung.java.set;
22

3-
import static org.junit.Assert.assertEquals;
4-
import static org.junit.Assert.assertTrue;
3+
import org.junit.Test;
54

6-
import java.util.ConcurrentModificationException;
7-
import java.util.HashSet;
8-
import java.util.Iterator;
9-
import java.util.Set;
10-
import java.util.TreeSet;
5+
import java.util.*;
116

12-
import org.junit.Test;
7+
import static org.junit.Assert.assertEquals;
8+
import static org.junit.Assert.assertTrue;
139

1410
public class SetTest {
1511

@@ -44,22 +40,22 @@ public void givenHashSet_whenAddNullObject_thenOK() {
4440

4541
@Test
4642
public void givenHashSetAndTreeSet_whenAddObjects_thenHashSetIsFaster() {
47-
Set<String> set = new HashSet<>();
48-
long startTime = System.nanoTime();
49-
set.add("Baeldung");
50-
set.add("is");
51-
set.add("Awesome");
52-
long endTime = System.nanoTime();
53-
long duration1 = (endTime - startTime);
5443

55-
Set<String> set2 = new TreeSet<>();
56-
startTime = System.nanoTime();
57-
set2.add("Baeldung");
58-
set2.add("is");
59-
set2.add("Awesome");
60-
endTime = System.nanoTime();
61-
long duration2 = (endTime - startTime);
62-
assertTrue(duration1 < duration2);
44+
long hashSetInsertionTime = measureExecution(() -> {
45+
Set<String> set = new HashSet<>();
46+
set.add("Baeldung");
47+
set.add("is");
48+
set.add("Awesome");
49+
});
50+
51+
long TreeSetInsertionTime = measureExecution(() -> {
52+
Set<String> set = new TreeSet<>();
53+
set.add("Baeldung");
54+
set.add("is");
55+
set.add("Awesome");
56+
});
57+
58+
assertTrue(hashSetInsertionTime < TreeSetInsertionTime);
6359
}
6460

6561
@Test
@@ -86,4 +82,13 @@ public void givenHashSet_whenModifyWhenIterator_thenFailFast() {
8682
it.next();
8783
}
8884
}
85+
86+
private static long measureExecution(Runnable task) {
87+
long startTime = System.nanoTime();
88+
task.run();
89+
long endTime = System.nanoTime();
90+
long executionTime = endTime - startTime;
91+
System.out.println(executionTime);
92+
return executionTime;
93+
}
8994
}

0 commit comments

Comments
 (0)