Skip to content

Commit

Permalink
Conainers in Depth: Exercise 34
Browse files Browse the repository at this point in the history
  • Loading branch information
kean0212 committed May 30, 2017
1 parent 8870670 commit 13937a4
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
7 changes: 7 additions & 0 deletions ContainersInDepth/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -234,3 +234,10 @@ because an `ArrayList` must create space and copy all its references forward dur
**Note**:
1. We can instantiate an abstract class by implementing the abstract method in an anonymous class, like
[ListPerformance.java](https://github.com/kean0212/Thinking-In-Java-Notes/blob/master/ContainersInDepth/ListPerformance.java#L22).

### Choosing between Sets
1. `HashSet` is used for 'insertion' and 'searching'.

2. `TreeSet` is used for sorted set.

3. `LinkedHashSet` is for maintaining inserted order.
61 changes: 61 additions & 0 deletions ContainersInDepth/SetPerformance.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import java.util.List;
import java.util.Set;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.HashSet;
import java.util.TreeSet;
import java.util.LinkedHashSet;

public class SetPerformance {
static List<Test<Set<String>>> tests = new ArrayList<>();

static {
tests.add(new Test<Set<String>>("add") {
int test(Set<String> set, TestParam testParam) {
int loops = testParam.loops;
int size = testParam.size;
for (int i = 0; i < loops; ++i) {
set.clear();
for (int j = 0; j < size; ++j) {
set.add("hello");
}
}
return loops * size;
}
});
tests.add(new Test<Set<String>>("contains") {
int test(Set<String> set, TestParam testParam) {
int loops = testParam.loops;
int size = testParam.size * 2;
for (int i = 0; i < loops; ++i) {
for (int j = 0; j < size; ++j) {
set.contains("hello");
}
}
return loops * size;
}
});
tests.add(new Test<Set<String>>("iterate") {
int test(Set<String> set, TestParam testParam) {
int loops = testParam.loops * 10;
for (int i = 0; i < loops; ++i) {
Iterator<String> iterator = set.iterator();
while (iterator.hasNext()) {
iterator.next();
}
}
return loops * set.size();
}
});
}

public static void main(String[] args) {
if (args.length > 0) {
Tester.defaultTestParams = TestParam.array(args);
}
Tester.fieldWidth = 10;
Tester.run(new HashSet<String>(), tests);
Tester.run(new TreeSet<String>(), tests);
Tester.run(new LinkedHashSet<String>(), tests);
}
}

0 comments on commit 13937a4

Please sign in to comment.