Skip to content

Method: push(Optional)

1: package de.fhdw.gaming.memory.impl;
2:
3: import java.util.ArrayList;
4: import java.util.List;
5: import java.util.Optional;
6:
7: import de.fhdw.gaming.memory.ShiftList;
8:
9: /**
10: * Organises a list of Optional doubles, allowing to set a maximum size for is.
11: */
12: public class MemoryShiftListImpl implements ShiftList {
13:
14: /**
15: * The number of outcomes this list can save.
16: */
17: private int length = 0;
18:
19: /**
20: * Saves the outcomes of a player given as Optional<Double> as List.
21: */
22: private List<Optional<Double>> memory = new ArrayList<Optional<Double>>();
23:
24: /**
25: * Creates a MemoryShiftListImpl object with the default length of 0.
26: */
27: public MemoryShiftListImpl() {
28: }
29:
30: /**
31: * Creates a MemoryShiftListImpl object able to save up to length outcomes.
32: *
33: * @param length
34: */
35: public MemoryShiftListImpl(int length) {
36: this.length = length;
37: }
38:
39: /**
40: * Adds an outcome as Optional<Double> to the list. If the list is already full,
41: * the oldest outcome will be deleted before adding the new one.
42: *
43: * @param input
44: */
45: @Override
46: public void push(Optional<Double> input) {
47:
48:• if (length == -1) {
49: memory.add(input);
50:• } else if (length < -1) {
51: // throw error
52:• } else if (length == memory.size()) {
53: memory.remove(0);
54: memory.add(input);
55:• } else if (length > memory.size()) {
56: memory.add(input);
57: }
58:
59: }
60:
61: /**
62: * Returns the list of all recorded outcomes as Optional<Double>.
63: */
64: @Override
65: public List<Optional<Double>> show() {
66: return this.memory;
67: }
68:
69: /**
70: * Determines how many outcomes can be saved in the list displyyed by the show() method.
71: * If there are too many outcomes saved this will delete the oldest outcome until
72: * the number of outcomes is equal to the length.
73: *
74: * @param length
75: */
76: @Override
77: public void setLength(int length) {
78: this.length = length;
79: if (length < -1) {
80: throw new IllegalArgumentException("The length value entered cannot be used. The value must be >= -1.");
81: }
82: while (length < memory.size() && length != -1) {
83: memory.remove(0);
84: }
85: }
86:
87: /**
88: * Returns the number of outcomes that can be saves.
89: */
90: @Override
91: public int getLength() {
92: return length;
93: }
94:
95: }