Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 28 additions & 23 deletions core-java/src/test/java/com/baeldung/java/set/SetTest.java
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
package com.baeldung.java.set;

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

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

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

public class SetTest {

Expand Down Expand Up @@ -44,22 +40,22 @@ public void givenHashSet_whenAddNullObject_thenOK() {

@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);
long hashSetInsertionTime = measureExecution(() -> {
Set<String> set = new HashSet<>();
set.add("Baeldung");
set.add("is");
set.add("Awesome");
});

long TreeSetInsertionTime = measureExecution(() -> {
Set<String> set = new TreeSet<>();
set.add("Baeldung");
set.add("is");
set.add("Awesome");
});

assertTrue(hashSetInsertionTime < TreeSetInsertionTime);
}

@Test
Expand All @@ -86,4 +82,13 @@ public void givenHashSet_whenModifyWhenIterator_thenFailFast() {
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;
}
}