-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExample119.java
More file actions
71 lines (63 loc) · 2.13 KB
/
Example119.java
File metadata and controls
71 lines (63 loc) · 2.13 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
// Example 119 from page 91
//
import java.util.*;
/*
Since it is illegal to create an array by new T[SIZE] in class Log<T>,
we must pass a suitable array to the constructor.
Similarly, method getAll() could not return an array of type T[],
because it is not allowed to create such an array. Also, it cannot
use res.toArray(log) to create an array with the right element type,
as that would overwrite the log array...
*/
class Log<T> {
private final int size;
private static int instanceCount = 0;
private int count = 0;
private T[] log;
public Log(T[] log) {
this.log = log;
this.size = log.length;
instanceCount++;
}
public static int getInstanceCount() { return instanceCount; }
public void add(T msg) { log[count++ % size] = msg; }
public int getCount() { return count; }
public T getLast() {
// Return the last log entry, or null if nothing logged yet
return count==0 ? null : log[(count-1)%size];
}
public void setLast(T value) {
// Update the last log entry, or create one if nothing logged yet
if (count==0)
log[count++] = value;
else
log[(count-1)%size] = value;
}
public ArrayList<T> getAll() {
ArrayList<T> res = new ArrayList<T>();
int stop = Math.min(count, size);
for (int i=0; i<stop; i++)
res.add(log[(count-stop+i) % size]);
return res;
}
}
class Example119 {
public static void main(String[] args) {
// Log<String> log1 = new Log<String>(new String[5]);
Log<String> log1 = new Log<>(new String[5]); // Shorthand for the above
log1.add("Reboot");
log1.add("Coffee");
// Log<Date> log2 = new Log<Date>(new Date[5]); // Shorthand for the above
Log<Date> log2 = new Log<>(new Date[5]);
log2.add(new Date()); // now
log2.add(new Date(new Date().getTime() + 60*60*1000)); // now + 1 hour
ArrayList<Date> dts = log2.getAll();
// Printing both logs:
for (String s : log1.getAll())
System.out.print(s + " ");
System.out.println();
for (Date dt : dts)
System.out.print(dt + " ");
System.out.println();
}
}