1 | package de.ugoe.cs.quest.usageprofiles;
|
---|
2 |
|
---|
3 | import java.security.InvalidParameterException;
|
---|
4 | import java.util.LinkedList;
|
---|
5 | import java.util.List;
|
---|
6 |
|
---|
7 | /**
|
---|
8 | * <p>
|
---|
9 | * Implements a round-trip buffered memory of a specified length that can be used to remember the
|
---|
10 | * recent history. Every event that happend longer ago than the length of the memory is forgotten,
|
---|
11 | * hence the memory is incomplete.
|
---|
12 | * </p>
|
---|
13 | *
|
---|
14 | * @author Steffen Herbold
|
---|
15 | * @version 1.0
|
---|
16 | *
|
---|
17 | * @param <T>
|
---|
18 | * Type which is memorized.
|
---|
19 | */
|
---|
20 | public class IncompleteMemory<T> implements IMemory<T> {
|
---|
21 |
|
---|
22 | /**
|
---|
23 | * <p>
|
---|
24 | * Maximum length of the memory.
|
---|
25 | * </p>
|
---|
26 | */
|
---|
27 | private int length;
|
---|
28 |
|
---|
29 | /**
|
---|
30 | * <p>
|
---|
31 | * Internal storage of the history.
|
---|
32 | * </p>
|
---|
33 | */
|
---|
34 | private List<T> history;
|
---|
35 |
|
---|
36 | /**
|
---|
37 | * <p>
|
---|
38 | * Constructor. Creates a new IncompleteMemory.
|
---|
39 | * </p>
|
---|
40 | *
|
---|
41 | * @param length
|
---|
42 | * number of recent events that are remembered
|
---|
43 | * @throws InvalidParameterException
|
---|
44 | * This exception is thrown if the length is smaller than 1
|
---|
45 | */
|
---|
46 | public IncompleteMemory(int length) {
|
---|
47 | if (length < 1) {
|
---|
48 | throw new InvalidParameterException("Length of IncompleteMemory must be at least 1.");
|
---|
49 | }
|
---|
50 | this.length = length;
|
---|
51 | history = new LinkedList<T>();
|
---|
52 | }
|
---|
53 |
|
---|
54 | /*
|
---|
55 | * (non-Javadoc)
|
---|
56 | *
|
---|
57 | * @see de.ugoe.cs.quest.usageprofiles.IMemory#add(java.lang.Object)
|
---|
58 | */
|
---|
59 | @Override
|
---|
60 | public void add(T state) {
|
---|
61 | if (history.size() == length) {
|
---|
62 | history.remove(0);
|
---|
63 | }
|
---|
64 | history.add(state);
|
---|
65 | }
|
---|
66 |
|
---|
67 | /*
|
---|
68 | * (non-Javadoc)
|
---|
69 | *
|
---|
70 | * @see de.ugoe.cs.quest.usageprofiles.IMemory#getLast(int)
|
---|
71 | */
|
---|
72 | @Override
|
---|
73 | public List<T> getLast(int num) {
|
---|
74 | if (num < 1) {
|
---|
75 | return new LinkedList<T>();
|
---|
76 | }
|
---|
77 | else {
|
---|
78 | return new LinkedList<T>(history.subList(Math.max(0, history.size() - num),
|
---|
79 | history.size())); // defensive copy
|
---|
80 | }
|
---|
81 | }
|
---|
82 |
|
---|
83 | /**
|
---|
84 | * <p>
|
---|
85 | * Returns the current length of the memory. This can be less than {@link #length}, if the
|
---|
86 | * overall history is less than {@link #length}.
|
---|
87 | * </p>
|
---|
88 | *
|
---|
89 | * @return length of the current memory
|
---|
90 | */
|
---|
91 | public int getLength() {
|
---|
92 | return history.size();
|
---|
93 | }
|
---|
94 | }
|
---|