├── .gitignore
├── .idea
├── compiler.xml
├── libraries
│ ├── Maven__junit_junit_4_12.xml
│ └── Maven__org_hamcrest_hamcrest_core_1_3.xml
├── misc.xml
├── modules.xml
├── uiDesigner.xml
└── vcs.xml
├── README.md
├── ThinkingInJavaNote.iml
├── pom.xml
└── src
├── main
└── java
│ ├── ch14typeinfo
│ └── DynamicProxyDemo.java
│ ├── ch15generic
│ ├── IterableFibonacci.java
│ └── LinkedStack.java
│ ├── ch16array
│ ├── ArrayDefaultInitializer.java
│ └── ArrayEquals.java
│ ├── ch17containers
│ ├── CountedString.java
│ ├── Ex1.java
│ ├── Ex11.java
│ ├── Ex7.java
│ ├── Ex8.java
│ ├── Groundhog.java
│ ├── Groundhog2.java
│ ├── ListPerformance.java
│ ├── MapPerformance.java
│ ├── Prediction.java
│ ├── SetPerformance.java
│ ├── SimpleHashMap.java
│ ├── SimpleHashMap20.java
│ ├── SimpleHashMap22.java
│ ├── SlowMap.java
│ ├── SlowMap17.java
│ ├── SpringDetector.java
│ ├── SpringDetector2.java
│ ├── Test.java
│ ├── TestParam.java
│ └── Tester.java
│ ├── ch21concurrency
│ ├── AtomicEvenGenerator.java
│ ├── AtomicIntegerTest.java
│ ├── AtomicityTest.java
│ ├── AttempLocking.java
│ ├── CachedThreadPool.java
│ ├── CallableDemo.java
│ ├── CaptureUncaughtException.java
│ ├── CountDownLatchDemo.java
│ ├── CriticalSection.java
│ ├── DaemonFromFactory.java
│ ├── Daemons.java
│ ├── DaemonsDontRunFinally.java
│ ├── DeadlockingDiningPhilosophers.java
│ ├── DualSync.java
│ ├── EvenChecker.java
│ ├── EvenGenerator.java
│ ├── Ex14Timer.java
│ ├── Ex15SyncTest.java
│ ├── Ex16LockTest.java
│ ├── Ex18Interruption.java
│ ├── Ex1Runner.java
│ ├── Ex21WaitAndNotify.java
│ ├── Ex22BusyWaitAndBetterWait.java
│ ├── Ex27Restaurant.java
│ ├── Ex30PipeIOUsingBlockingQueue.java
│ ├── Ex5FibonacciCallable.java
│ ├── Ex6RandomSleep.java
│ ├── ExceptionThread.java
│ ├── FixedDiningPhilosophers.java
│ ├── FixedThreadPool.java
│ ├── HorseRace.java
│ ├── IntGenerator.java
│ ├── Interrupting.java
│ ├── Joining.java
│ ├── LiftOff.java
│ ├── MoreBasicThreads.java
│ ├── MutexEvenGenerator.java
│ ├── NIOInterruption.java
│ ├── NaiveExceptionHandling.java
│ ├── NotifyVsNotifyAll.java
│ ├── OrnamentalGarden.java
│ ├── PriorityBlockingQueueDemo.java
│ ├── ResponsiveUI.java
│ ├── Restaurant.java
│ ├── SerialNumberChecker.java
│ ├── SerialNumberGenerator.java
│ ├── SettingDefaultHandler.java
│ ├── SimpleDaemons.java
│ ├── SingleThreadPool.java
│ ├── SynchronizedEvenGenerator.java
│ ├── TestCyclicBarrier.java
│ ├── TestingBlockingQueues.java
│ ├── ThreadVariations.java
│ ├── ToastOMatic.java
│ └── WaxOMatic.java
│ ├── main_for_test
│ └── MainForTest.java
│ └── util
│ ├── CollectionData.java
│ ├── CountingGenerator.java
│ ├── CountingIntegerList.java
│ ├── CountingMapData.java
│ ├── Countries.java
│ ├── DaemonThreadFactory.java
│ ├── Generated.java
│ ├── Generator.java
│ ├── MapEntry.java
│ ├── Maps.java
│ ├── Print.java
│ ├── RandomGenerator.java
│ └── TextFile.java
└── test
└── java
└── ch15generic
└── LinkedStackTest.java
/.gitignore:
--------------------------------------------------------------------------------
1 | # Compiled class file
2 | *.class
3 |
4 | # Log file
5 | *.log
6 |
7 | # BlueJ files
8 | *.ctxt
9 |
10 | # Mobile Tools for Java (J2ME)
11 | .mtj.tmp/
12 |
13 | # Package Files #
14 | *.jar
15 | *.war
16 | *.ear
17 | *.zip
18 | *.tar.gz
19 | *.rar
20 |
21 | .idea/workspace.xml
22 |
23 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
24 | hs_err_pid*
25 |
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/.idea/libraries/Maven__junit_junit_4_12.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/.idea/libraries/Maven__org_hamcrest_hamcrest_core_1_3.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/uiDesigner.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | -
6 |
7 |
8 | -
9 |
10 |
11 | -
12 |
13 |
14 | -
15 |
16 |
17 | -
18 |
19 |
20 |
21 |
22 |
23 | -
24 |
25 |
26 |
27 |
28 |
29 | -
30 |
31 |
32 |
33 |
34 |
35 | -
36 |
37 |
38 |
39 |
40 |
41 | -
42 |
43 |
44 |
45 |
46 | -
47 |
48 |
49 |
50 |
51 | -
52 |
53 |
54 |
55 |
56 | -
57 |
58 |
59 |
60 |
61 | -
62 |
63 |
64 |
65 |
66 | -
67 |
68 |
69 |
70 |
71 | -
72 |
73 |
74 | -
75 |
76 |
77 |
78 |
79 | -
80 |
81 |
82 |
83 |
84 | -
85 |
86 |
87 |
88 |
89 | -
90 |
91 |
92 |
93 |
94 | -
95 |
96 |
97 |
98 |
99 | -
100 |
101 |
102 | -
103 |
104 |
105 | -
106 |
107 |
108 | -
109 |
110 |
111 | -
112 |
113 |
114 |
115 |
116 | -
117 |
118 |
119 | -
120 |
121 |
122 |
123 |
124 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Thinking in Java Notes
2 | 敲一些课后习题和sample code
3 |
--------------------------------------------------------------------------------
/ThinkingInJavaNote.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | wenzheGroup
8 | ThinkingInJavaNote
9 | 1.0-SNAPSHOT
10 |
11 |
12 |
13 | org.apache.maven.plugins
14 | maven-compiler-plugin
15 |
16 | 1.8
17 | 1.8
18 |
19 |
20 |
21 |
22 |
23 |
24 | junit
25 | junit
26 | RELEASE
27 |
28 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/src/main/java/ch14typeinfo/DynamicProxyDemo.java:
--------------------------------------------------------------------------------
1 | package ch14typeinfo;
2 |
3 | import java.lang.reflect.InvocationHandler;
4 | import java.lang.reflect.Method;
5 | import java.lang.reflect.Proxy;
6 |
7 | public class DynamicProxyDemo {
8 | public static void main(String[] args) {
9 | Subject realSubject = new RealSubject();
10 | ProxyHandler proxyHandler = new ProxyHandler(realSubject);
11 |
12 | // Class clazz = Proxy.getProxyClass(
13 | // RealSubject.class.getClassLoader(),
14 | // RealSubject.class.getInterfaces());
15 | // System.out.println("Clazz " + clazz);
16 | // System.out.println("Clazz methods " + clazz.getMethods());
17 | // System.out.println("Clazz super class " + clazz.getSuperclass());
18 |
19 | Subject proxyObject = (Subject)Proxy.newProxyInstance(
20 | RealSubject.class.getClassLoader(),
21 | RealSubject.class.getInterfaces(),
22 | proxyHandler);
23 | proxyObject.request();
24 |
25 | proxyObject.anotherRequest();
26 | }
27 | }
28 |
29 | /**
30 | * 接口
31 | */
32 | interface Subject{
33 | String request();
34 | void anotherRequest();
35 | }
36 |
37 | /**
38 | * 委托类
39 | */
40 | class RealSubject implements Subject{
41 | @Override
42 | public String request(){
43 | System.out.println("====RealSubject request====");
44 | return "RealSubject.request()";
45 | }
46 |
47 | @Override
48 | public void anotherRequest() {
49 | System.out.println("====RealSubject anotherRequest====");
50 | }
51 | }
52 |
53 | /**
54 | * 代理类的调用处理器
55 | */
56 | class ProxyHandler implements InvocationHandler {
57 |
58 | private Subject subject;
59 | public ProxyHandler(Subject subject) {
60 | this.subject = subject;
61 | }
62 |
63 | @Override
64 | public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
65 | System.out.println("Before " + method);
66 | Object result = method.invoke(subject, args);
67 | System.out.println("After " + method + ", Result " + result);
68 | return result;
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/src/main/java/ch15generic/IterableFibonacci.java:
--------------------------------------------------------------------------------
1 | package ch15generic;
2 |
3 | import java.util.Iterator;
4 |
5 | public class IterableFibonacci implements Iterable{
6 | int size;
7 | int[] cache;
8 | int position = 0;
9 |
10 | public IterableFibonacci(int size) {
11 | if (size <= 0) throw new IllegalArgumentException();
12 |
13 | this.size = size;
14 | cache = new int[size];
15 |
16 | cache[0] = 1;
17 | if (size > 1)
18 | cache[1] = 1;
19 | }
20 |
21 | private class FibonacciIterable implements Iterator {
22 |
23 | @Override
24 | public boolean hasNext() {
25 | return position < size;
26 | }
27 |
28 | @Override
29 | public Integer next() {
30 | if (position < 2)
31 | return cache[position++];
32 |
33 | int result = cache[position - 2] + cache[position - 1];
34 | cache[position++] = result;
35 |
36 | return result;
37 | }
38 | }
39 | @Override
40 | public Iterator iterator() {
41 | return new FibonacciIterable();
42 | }
43 | }
44 |
45 | class IterableFibonacciTester {
46 | public static void main(String[] args) {
47 | for (int i: new IterableFibonacci(5)) {
48 | System.out.print(i+", ");
49 | }
50 | }
51 | }
--------------------------------------------------------------------------------
/src/main/java/ch15generic/LinkedStack.java:
--------------------------------------------------------------------------------
1 | package ch15generic;
2 |
3 | /**
4 | * Created by DengWenzhe on 3/5/17.
5 | */
6 | public class LinkedStack {
7 | // Inner helper class
8 | private class Node {
9 | T item;
10 | Node next;
11 |
12 | Node() { }
13 |
14 | Node(T item, Node next) {
15 | this.item = item;
16 | this.next = next;
17 | }
18 |
19 | // boolean isEnd() {
20 | // return item == null && next == null;
21 | // }
22 |
23 | @Override
24 | public String toString() {
25 | return "Node " + item;
26 | }
27 |
28 | }
29 |
30 | Node top = null;
31 | int size = 0;
32 |
33 | public void push(T item) {
34 | Node newNode = new Node(item, top);
35 | top = newNode;
36 | size++;
37 | }
38 |
39 | public T pop() {
40 | if (isEmpty())
41 | return null;
42 |
43 | T result = top.item;
44 | top = top.next;
45 |
46 | size--;
47 | return result;
48 | }
49 |
50 | public boolean isEmpty() {
51 | return top == null;
52 | }
53 |
54 | public int size() {
55 | return size;
56 | }
57 | }
58 |
59 | class LinkedStackTester {
60 | public static void main(String[] args) {
61 | String[] arr = "a b c d e f gg".split(" ");
62 | LinkedStack stack = new LinkedStack<>();
63 | for (String s: arr) {
64 | stack.push(s);
65 | }
66 |
67 | while (!stack.isEmpty()) {
68 | System.out.println(stack.pop());
69 | }
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/src/main/java/ch16array/ArrayDefaultInitializer.java:
--------------------------------------------------------------------------------
1 | package ch16array;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * Created by DengWenzhe on 3/9/17.
7 | */
8 | public class ArrayDefaultInitializer {
9 |
10 | public static void main(String[] args) {
11 | int[] a = new int[3];
12 | System.out.println("a " + Arrays.toString(a));
13 |
14 | //int[] b = new int[]; compile error
15 | //System.out.println(Arrays.toString(b));
16 |
17 | int[][] b = new int[3][4];
18 | System.out.println("b " + Arrays.deepToString(b));
19 |
20 | int[][] c = new int[3][];
21 | System.out.println("c " + Arrays.deepToString(c));
22 |
23 | int[][][] d = new int[3][4][5];
24 | System.out.println("d " + Arrays.deepToString(d));
25 |
26 | int[][][] e = new int[3][4][];
27 | System.out.println("e " + Arrays.deepToString(e));
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/ch16array/ArrayEquals.java:
--------------------------------------------------------------------------------
1 | package ch16array;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * Created by DengWenzhe on 3/9/17.
7 | */
8 | public class ArrayEquals {
9 | int val;
10 |
11 | public ArrayEquals(int val) {
12 | this.val = val;
13 | }
14 | }
15 |
16 | class ArrayEqualsOverride {
17 | int val;
18 |
19 | public ArrayEqualsOverride(int val) {
20 | this.val = val;
21 | }
22 |
23 | @Override
24 | public boolean equals(Object another) {
25 | if (another == null)
26 | return false;
27 |
28 | ArrayEqualsOverride other;
29 | if (another instanceof ArrayEqualsOverride)
30 | other = (ArrayEqualsOverride) another;
31 | else
32 | return false;
33 |
34 | return other.val == this.val;
35 | }
36 | }
37 |
38 | class ArrayEqualsTester {
39 |
40 | public static void main(String[] args) {
41 | ArrayEquals[] a = new ArrayEquals[] {
42 | new ArrayEquals(1),
43 | new ArrayEquals(2),
44 | new ArrayEquals(3)
45 | };
46 |
47 | ArrayEquals[] b = new ArrayEquals[] {
48 | new ArrayEquals(1),
49 | new ArrayEquals(2),
50 | new ArrayEquals(3)
51 | };
52 |
53 | System.out.println("a equals b " + Arrays.equals(a, b));
54 |
55 | ArrayEqualsOverride[] c = new ArrayEqualsOverride[] {
56 | new ArrayEqualsOverride(1),
57 | new ArrayEqualsOverride(2),
58 | new ArrayEqualsOverride(3)
59 | };
60 |
61 | ArrayEqualsOverride[] d = new ArrayEqualsOverride[] {
62 | new ArrayEqualsOverride(1),
63 | new ArrayEqualsOverride(2),
64 | new ArrayEqualsOverride(3)
65 | };
66 |
67 | System.out.println("c equals d " + Arrays.equals(c, d));
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/src/main/java/ch17containers/CountedString.java:
--------------------------------------------------------------------------------
1 | package ch17containers;
2 |
3 | import java.util.*;
4 | import static util.Print.*;
5 |
6 | public class CountedString {
7 | private static List created =
8 | new ArrayList();
9 | private String s;
10 | private int id = 0;
11 | public CountedString(String str) {
12 | s = str;
13 | created.add(s);
14 | // id is the total number of instances
15 | // of this string in use by CountedString:
16 | for(String s2 : created)
17 | if(s2.equals(s))
18 | id++;
19 | }
20 | public String toString() {
21 | return "String: " + s + " id: " + id +
22 | " hashCode(): " + hashCode();
23 | }
24 | public int hashCode() {
25 | // The very simple approach:
26 | // return s.hashCode() * id;
27 | // Using Joshua Bloch's recipe:
28 | int result = 17;
29 | result = 37 * result + s.hashCode();
30 | result = 37 * result + id;
31 | return result;
32 | }
33 | public boolean equals(Object o) {
34 | return o instanceof CountedString &&
35 | s.equals(((CountedString)o).s) &&
36 | id == ((CountedString)o).id;
37 | }
38 | public static void main(String[] args) {
39 | Map map =
40 | new HashMap();
41 | CountedString[] cs = new CountedString[5];
42 | for(int i = 0; i < cs.length; i++) {
43 | cs[i] = new CountedString("hi");
44 | map.put(cs[i], i); // Autobox int -> Integer
45 | }
46 | print(map);
47 | for(CountedString cstring : cs) {
48 | print("Looking up " + cstring);
49 | print(map.get(cstring));
50 | }
51 | }
52 | } /* Output: (Sample)
53 | {String: hi id: 4 hashCode(): 146450=3, String: hi id: 1 hashCode(): 146447=0, String: hi id: 3 hashCode(): 146449=2, String: hi id: 5 hashCode(): 146451=4, String: hi id: 2 hashCode(): 146448=1}
54 | Looking up String: hi id: 1 hashCode(): 146447
55 | 0
56 | Looking up String: hi id: 2 hashCode(): 146448
57 | 1
58 | Looking up String: hi id: 3 hashCode(): 146449
59 | 2
60 | Looking up String: hi id: 4 hashCode(): 146450
61 | 3
62 | Looking up String: hi id: 5 hashCode(): 146451
63 | 4
64 | */
65 |
--------------------------------------------------------------------------------
/src/main/java/ch17containers/Ex1.java:
--------------------------------------------------------------------------------
1 | package ch17containers;
2 |
3 | import java.util.*;
4 | import static util.Countries.DATA;
5 |
6 | /**
7 | * Created by DengWenzhe on 3/19/17.
8 | */
9 | public class Ex1 {
10 | public static void main(String[] args) {
11 | List arrayList = new ArrayList<>();
12 | List linkedList = new LinkedList<>();
13 |
14 | for (String[] country: DATA) {
15 | arrayList.add(country[0]);
16 | linkedList.add(country[1]);
17 | }
18 | Collections.sort(arrayList);
19 | Collections.sort(linkedList);
20 |
21 | System.out.print("Countries: ");
22 | System.out.println(arrayList);
23 | System.out.print("Capitals: ");
24 | System.out.println(linkedList);
25 |
26 | for (int i = 0 ; i < 3; i++) {
27 | Collections.shuffle(arrayList);
28 | Collections.shuffle(linkedList);
29 |
30 | System.out.print("Countries: ");
31 | System.out.println(arrayList);
32 | System.out.print("Capitals: ");
33 | System.out.println(linkedList);
34 | }
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/ch17containers/Ex11.java:
--------------------------------------------------------------------------------
1 | package ch17containers;
2 |
3 | import java.util.Comparator;
4 | import java.util.PriorityQueue;
5 | import java.util.Queue;
6 | import java.util.concurrent.ThreadLocalRandom;
7 |
8 | /**
9 | * Created by DengWenzhe on 3/19/17.
10 | */
11 | public class Ex11 {
12 | public static void main(String[] args) {
13 | Queue- heap = new PriorityQueue<>();
14 | for (int i = 0; i < 10; i++) {
15 | heap.offer(new Item());
16 | }
17 |
18 | while (!heap.isEmpty()) {
19 | System.out.print(heap.poll().val + ", ");
20 | }
21 | }
22 | }
23 |
24 | class Item implements Comparable
- {
25 | int val = ThreadLocalRandom.current().nextInt(100);
26 |
27 | @Override
28 | public int compareTo(Item o) {
29 | return Integer.compare(val, o.val);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/ch17containers/Ex7.java:
--------------------------------------------------------------------------------
1 | package ch17containers;
2 |
3 | import java.util.*;
4 | import util.Countries;
5 |
6 | /**
7 | * Created by DengWenzhe on 3/19/17.
8 | */
9 | public class Ex7 {
10 | public static void main(String[] args) {
11 | List arrayList = new ArrayList<>(Countries.names(10));
12 | List linkedList = new LinkedList<>(Countries.names(10));
13 |
14 | System.out.println("arrayList " + arrayList);
15 | System.out.println("linkedList " + linkedList);
16 |
17 | ListIterator li1 = arrayList.listIterator(arrayList.size());
18 | ListIterator li2 = linkedList.listIterator();
19 |
20 | int step = 0;
21 | while (li1.hasPrevious() && li2.hasNext()) {
22 | String str1 = li1.previous();
23 | String str2 = li2.next();
24 |
25 | if (step % 2 == 1) {
26 | li1.add(str2);
27 | }
28 | step++;
29 | }
30 |
31 | System.out.println("arrayList " + arrayList);
32 | System.out.println("linkedList " + linkedList);
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/ch17containers/Ex8.java:
--------------------------------------------------------------------------------
1 | package ch17containers;
2 |
3 | /**
4 | * Created by DengWenzhe on 3/19/17.
5 | */
6 | public class Ex8 {
7 | public static void main(String[] args) {
8 | Node node1 = new Node("node1");
9 | Node node2 = new Node("node2");
10 | Node node3 = new Node("node3");
11 |
12 | SList sList = new SList<>();
13 | SListIterator iter = sList.listIterator();
14 | iter.insert("1");
15 | iter.insert("2");
16 | iter.insert("3");
17 | iter.insert("4");
18 |
19 | System.out.println(sList);
20 |
21 | iter = sList.listIterator();
22 | iter.remove();
23 | System.out.println(sList);
24 |
25 | iter.remove();
26 | System.out.println(sList);
27 | }
28 | }
29 | class SList {
30 | Node dummyHead = new Node(null);
31 |
32 | SListIterator listIterator() {
33 | return new SListIterator(dummyHead);
34 | }
35 |
36 | @Override
37 | public String toString() {
38 | StringBuffer sb = new StringBuffer();
39 | SListIterator iter = listIterator();
40 | while (iter.hasNext()) {
41 | sb.append("Node ");
42 | sb.append(iter.next());
43 | sb.append(", ");
44 | }
45 |
46 | return sb.toString();
47 | }
48 | }
49 |
50 | class SListIterator {
51 | Node current = null;
52 | public SListIterator(Node node) {
53 | current = node;
54 | }
55 |
56 | public boolean hasNext() {
57 | return current.next != null;
58 | }
59 |
60 | public E next() {
61 | current = current.next;
62 | return current.val;
63 | }
64 |
65 | public void insert(E element) {
66 | current.next = new Node(element, current.next);
67 | current = current.next;
68 | }
69 |
70 | public void remove() {
71 | if (current.next != null)
72 | current.next = current.next.next;
73 | }
74 | }
75 |
76 | class Node {
77 | E val;
78 | Node next;
79 |
80 | public Node(E val) {
81 | this.val = val;
82 | }
83 |
84 | public Node(E val, Node next) {
85 | this.val = val;
86 | this.next = next;
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/src/main/java/ch17containers/Groundhog.java:
--------------------------------------------------------------------------------
1 | package ch17containers;
2 |
3 | /**
4 | * Created by DengWenzhe on 3/22/17.
5 | */
6 | public class Groundhog {
7 | protected int number;
8 | public Groundhog(int n) { number = n; }
9 | public String toString() {
10 | return "Groundhog #" + number;
11 | }
12 | }
--------------------------------------------------------------------------------
/src/main/java/ch17containers/Groundhog2.java:
--------------------------------------------------------------------------------
1 | package ch17containers;
2 |
3 | public class Groundhog2 extends Groundhog{
4 |
5 | public Groundhog2(int n) {
6 | super(n);
7 | }
8 |
9 | @Override
10 | public int hashCode() {
11 | return number;
12 | }
13 |
14 | @Override
15 | public boolean equals(Object o) {
16 | return o instanceof Groundhog2 &&
17 | ((Groundhog2) o).number == this.number;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/main/java/ch17containers/ListPerformance.java:
--------------------------------------------------------------------------------
1 | package ch17containers;
2 |
3 | import java.util.*;
4 | import util.*;
5 |
6 | public class ListPerformance {
7 | static Random rand = new Random();
8 | static int reps = 1000;
9 | static List>> tests =
10 | new ArrayList>>();
11 | static List>> qTests =
12 | new ArrayList>>();
13 | static {
14 | tests.add(new Test
>("add") {
15 | int test(List list, TestParam tp) {
16 | int loops = tp.loops;
17 | int listSize = tp.size;
18 | for(int i = 0; i < loops; i++) {
19 | list.clear();
20 | for(int j = 0; j < listSize; j++)
21 | list.add(j);
22 | }
23 | return loops * listSize;
24 | }
25 | });
26 | tests.add(new Test>("get") {
27 | int test(List list, TestParam tp) {
28 | int loops = tp.loops * reps;
29 | int listSize = list.size();
30 | for(int i = 0; i < loops; i++)
31 | list.get(rand.nextInt(listSize));
32 | return loops;
33 | }
34 | });
35 | tests.add(new Test>("set") {
36 | int test(List list, TestParam tp) {
37 | int loops = tp.loops * reps;
38 | int listSize = list.size();
39 | for(int i = 0; i < loops; i++)
40 | list.set(rand.nextInt(listSize), 47);
41 | return loops;
42 | }
43 | });
44 | tests.add(new Test>("iteradd") {
45 | int test(List list, TestParam tp) {
46 | final int LOOPS = 1000000;
47 | int half = list.size() / 2;
48 | ListIterator it = list.listIterator(half);
49 | for(int i = 0; i < LOOPS; i++)
50 | it.add(47);
51 | return LOOPS;
52 | }
53 | });
54 | tests.add(new Test>("insert") {
55 | int test(List list, TestParam tp) {
56 | int loops = tp.loops;
57 | for(int i = 0; i < loops; i++)
58 | list.add(5, 47); // Minimize random-access cost
59 | return loops;
60 | }
61 | });
62 | tests.add(new Test>("remove") {
63 | int test(List list, TestParam tp) {
64 | int loops = tp.loops;
65 | int size = tp.size;
66 | for(int i = 0; i < loops; i++) {
67 | list.clear();
68 | list.addAll(new CountingIntegerList(size));
69 | while(list.size() > 5)
70 | list.remove(5); // Minimize random-access cost
71 | }
72 | return loops * size;
73 | }
74 | });
75 | // Tests for queue behavior:
76 | qTests.add(new Test>("addFirst") {
77 | int test(LinkedList list, TestParam tp) {
78 | int loops = tp.loops;
79 | int size = tp.size;
80 | for(int i = 0; i < loops; i++) {
81 | list.clear();
82 | for(int j = 0; j < size; j++)
83 | list.addFirst(47);
84 | }
85 | return loops * size;
86 | }
87 | });
88 | qTests.add(new Test>("addLast") {
89 | int test(LinkedList list, TestParam tp) {
90 | int loops = tp.loops;
91 | int size = tp.size;
92 | for(int i = 0; i < loops; i++) {
93 | list.clear();
94 | for(int j = 0; j < size; j++)
95 | list.addLast(47);
96 | }
97 | return loops * size;
98 | }
99 | });
100 | qTests.add(
101 | new Test>("rmFirst") {
102 | int test(LinkedList list, TestParam tp) {
103 | int loops = tp.loops;
104 | int size = tp.size;
105 | for(int i = 0; i < loops; i++) {
106 | list.clear();
107 | list.addAll(new CountingIntegerList(size));
108 | while(list.size() > 0)
109 | list.removeFirst();
110 | }
111 | return loops * size;
112 | }
113 | });
114 | qTests.add(new Test>("rmLast") {
115 | int test(LinkedList list, TestParam tp) {
116 | int loops = tp.loops;
117 | int size = tp.size;
118 | for(int i = 0; i < loops; i++) {
119 | list.clear();
120 | list.addAll(new CountingIntegerList(size));
121 | while(list.size() > 0)
122 | list.removeLast();
123 | }
124 | return loops * size;
125 | }
126 | });
127 | }
128 | static class ListTester extends Tester> {
129 | public ListTester(List container,
130 | List>> tests) {
131 | super(container, tests);
132 | }
133 | // Fill to the appropriate size before each test:
134 | @Override protected List initialize(int size){
135 | container.clear();
136 | container.addAll(new CountingIntegerList(size));
137 | return container;
138 | }
139 | // Convenience method:
140 | public static void run(List list,
141 | List>> tests) {
142 | new ListTester(list, tests).timedTest();
143 | }
144 | }
145 | public static void main(String[] args) {
146 | if(args.length > 0)
147 | Tester.defaultParams = TestParam.array(args);
148 | // Can only do these two tests on an array:
149 | Tester> arrayTest =
150 | new Tester>(null, tests.subList(1, 3)){
151 | // This will be called before each test. It
152 | // produces a non-resizeable array-backed list:
153 | @Override protected
154 | List initialize(int size) {
155 | Integer[] ia = Generated.array(Integer.class,
156 | new CountingGenerator.Integer(), size);
157 | return Arrays.asList(ia);
158 | }
159 | };
160 | arrayTest.setHeadline("Array as List");
161 | arrayTest.timedTest();
162 | Tester.defaultParams= TestParam.array(
163 | 10, 5000, 100, 5000, 1000, 1000, 10000, 200);
164 | if(args.length > 0)
165 | Tester.defaultParams = TestParam.array(args);
166 | ListTester.run(new ArrayList(), tests);
167 | ListTester.run(new LinkedList(), tests);
168 | ListTester.run(new Vector(), tests);
169 | Tester.fieldWidth = 12;
170 | Tester> qTest =
171 | new Tester>(
172 | new LinkedList(), qTests);
173 | qTest.setHeadline("Queue tests");
174 | qTest.timedTest();
175 | }
176 | } /* Output: (Sample)
177 | --- Array as List ---
178 | size get set
179 | 10 130 183
180 | 100 130 164
181 | 1000 129 165
182 | 10000 129 165
183 | --------------------- ArrayList ---------------------
184 | size add get set iteradd insert remove
185 | 10 121 139 191 435 3952 446
186 | 100 72 141 191 247 3934 296
187 | 1000 98 141 194 839 2202 923
188 | 10000 122 144 190 6880 14042 7333
189 | --------------------- LinkedList ---------------------
190 | size add get set iteradd insert remove
191 | 10 182 164 198 658 366 262
192 | 100 106 202 230 457 108 201
193 | 1000 133 1289 1353 430 136 239
194 | 10000 172 13648 13187 435 255 239
195 | ----------------------- Vector -----------------------
196 | size add get set iteradd insert remove
197 | 10 129 145 187 290 3635 253
198 | 100 72 144 190 263 3691 292
199 | 1000 99 145 193 846 2162 927
200 | 10000 108 145 186 6871 14730 7135
201 | -------------------- Queue tests --------------------
202 | size addFirst addLast rmFirst rmLast
203 | 10 199 163 251 253
204 | 100 98 92 180 179
205 | 1000 99 93 216 212
206 | 10000 111 109 262 384
207 | */
--------------------------------------------------------------------------------
/src/main/java/ch17containers/MapPerformance.java:
--------------------------------------------------------------------------------
1 | package ch17containers;
2 |
3 | import java.util.*;
4 |
5 | public class MapPerformance {
6 | static List>> tests =
7 | new ArrayList>>();
8 | static {
9 | tests.add(new Test