Repository navigation
Expand file tree
/
Copy pathSimpleListNodeBuilderPERF.java
More file actions
105 lines (79 loc) · 2.52 KB
/
Copy pathSimpleListNodeBuilderPERF.java
File metadata and controls
105 lines (79 loc) · 2.52 KB
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
import java.util.*;
public class SimpleListNodeBuilderPERF {
public static void main(String[] args) {
ListBuilder listBuilder = new ListBuilder();
// inputs:
String[] inputStringArray = new String[]{"1", "2", "3", "4"};
List<String> inputElements = Arrays.asList(inputStringArray);
try {
listBuilder.createList(inputElements);
} catch(Exception ex) {
System.out.println("Exception recieved from ListBuilder: " + ex);
}
listBuilder.printList();
// PERF: First create a fairly large linkedList (add say 1M (100,0000) elements)
listBuilder = new ListBuilder();
inputElements = new ArrayList<>();
for (int i=0; i<10000000; i++) {
inputElements.add(String.valueOf(i));
}
try {
listBuilder.createList(inputElements);
} catch (Exception e) {
System.out.println(e);
}
// PERF: Add one more new element to the last of the list
listBuilder.addValueToList("Hello");
}
}
class ListBuilder {
Node headNode = null;
Node lastNode = null;
public void createList(List<String> elementsToBeAdded) throws Exception {
// list could be empty
if (elementsToBeAdded.isEmpty()) {
throw new Exception("Empty inputs");
}
long startTime = System.currentTimeMillis();
// create the subsequent (HEAD) Nodes
for (int i=0; i<elementsToBeAdded.size(); i++) {
Node node = new Node();
node.value = elementsToBeAdded.get(i);
node.nextNode = null;
if (i == 0) {
headNode = node;
lastNode = node;
}
lastNode.nextNode = node;
lastNode = node;
}
long endTime = System.currentTimeMillis();
// PERF: Time taken?
System.out.println("Time taken to create the list: " + (endTime-startTime));
}
public void addValueToList(String value) {
// check length of the input string?
long startTime = System.currentTimeMillis();
Node node = new Node();
node.value = value;
node.nextNode = null;
lastNode.nextNode = node;
lastNode = node;
// PERF: Time taken?
long endTime = System.currentTimeMillis();
System.out.println("Time taken in adding one node to the last: " + (endTime-startTime));
}
public void printList() {
// empty list should not throw NPE or cause issues, handle it
// traverse the list, starting from the Headnode
Node node = headNode;
do {
System.out.println(node.value);
node = node.nextNode;
} while (!Objects.isNull(node));
}
}
class Node {
String value;
Node nextNode;
}