|
6 | 6 | import org.jetbrains.annotations.Nullable;
|
7 | 7 |
|
8 | 8 | public class JumpManager {
|
| 9 | + /** |
| 10 | + * Maximum number of elements to store in a jump list |
| 11 | + */ |
| 12 | + private static final int MAX_JUMPS = 100; |
9 | 13 |
|
10 |
| - private final List<JumpPosition> list = new ArrayList<>(); |
| 14 | + /** |
| 15 | + * This number of elements will be removed from the start if a list becomes bigger than MAX_JUMPS. |
| 16 | + * List grow most of the time, so removing should be done in big batches to not run very often. |
| 17 | + * Because of this, an effective jump history size will vary |
| 18 | + * from (MAX_JUMPS - LIST_SHRINK_COUNT) to MAX_JUMPS over time. |
| 19 | + */ |
| 20 | + private static final int LIST_SHRINK_COUNT = 50; |
| 21 | + |
| 22 | + private final List<JumpPosition> list = new ArrayList<>(MAX_JUMPS); |
11 | 23 | private int currentPos = 0;
|
12 | 24 |
|
13 |
| - public void addPosition(JumpPosition pos) { |
14 |
| - if (ignoreJump(pos)) { |
| 25 | + public void addPosition(@Nullable JumpPosition pos) { |
| 26 | + if (pos == null || ignoreJump(pos)) { |
15 | 27 | return;
|
16 | 28 | }
|
17 | 29 | currentPos++;
|
18 | 30 | if (currentPos >= list.size()) {
|
19 | 31 | list.add(pos);
|
| 32 | + if (list.size() >= MAX_JUMPS) { |
| 33 | + list.subList(0, LIST_SHRINK_COUNT).clear(); |
| 34 | + } |
20 | 35 | currentPos = list.size() - 1;
|
21 | 36 | } else {
|
| 37 | + // discard forward history after navigating back and jumping to a new place |
22 | 38 | list.set(currentPos, pos);
|
23 |
| - int size = list.size(); |
24 |
| - for (int i = currentPos + 1; i < size; i++) { |
25 |
| - list.set(i, null); |
26 |
| - } |
| 39 | + list.subList(currentPos + 1, list.size()).clear(); |
27 | 40 | }
|
28 | 41 | }
|
29 | 42 |
|
30 |
| - public void updateCurPosition(JumpPosition pos) { |
31 |
| - list.set(currentPos, pos); |
32 |
| - } |
33 |
| - |
34 | 43 | public int size() {
|
35 | 44 | return list.size();
|
36 | 45 | }
|
|
0 commit comments