root / org.gvsig.proj / branches / refactor2018 / org.gvsig.proj / org.gvsig.proj.swing / org.gvsig.proj.swing.impl / src / main / java / org / gvsig / proj / swing / impl / history / History.java @ 866
History | View | Annotate | Download (2.08 KB)
1 |
package org.gvsig.proj.swing.impl.history; |
---|---|
2 |
|
3 |
import java.util.Collections; |
4 |
import java.util.Iterator; |
5 |
import java.util.List; |
6 |
import java.util.concurrent.CopyOnWriteArrayList; |
7 |
|
8 |
import org.gvsig.proj.swing.RecentHistory; |
9 |
|
10 |
/**
|
11 |
* Stores a collection of objects, removing the oldest objects when the size
|
12 |
* of the collection grows beyond the allowed {@link #getMaxSize() maxSize}.
|
13 |
*
|
14 |
* This implementation is thread-safe. It is optimized for small collections of
|
15 |
* objects which are queried more often than modified. The collection is backed
|
16 |
* by a CopyOnWriteArrayList instance.
|
17 |
*
|
18 |
* @author Cesar Martinez Izquierdo
|
19 |
*
|
20 |
* @param <E>
|
21 |
*/
|
22 |
public class History<E> implements RecentHistory<E> { |
23 |
public static final int DEFAULT_MAX_SIZE = 8; |
24 |
private final CopyOnWriteArrayList<E> historyArray; |
25 |
private final int maxSize; |
26 |
|
27 |
public History() {
|
28 |
this(DEFAULT_MAX_SIZE);
|
29 |
} |
30 |
|
31 |
public History(int maxSize) { |
32 |
historyArray = new CopyOnWriteArrayList<E>(); |
33 |
this.maxSize = maxSize;
|
34 |
} |
35 |
|
36 |
public History(List<E> values, int maxSize) { |
37 |
historyArray = new CopyOnWriteArrayList<E>(values); |
38 |
this.maxSize = maxSize;
|
39 |
} |
40 |
|
41 |
/* (non-Javadoc)
|
42 |
* @see org.gvsig.proj.swing.impl.history.IHistory#getMaxSize()
|
43 |
*/
|
44 |
@Override
|
45 |
public int getMaxSize() { |
46 |
return this.maxSize; |
47 |
} |
48 |
|
49 |
/* (non-Javadoc)
|
50 |
* @see org.gvsig.proj.swing.impl.history.IHistory#add(E)
|
51 |
*/
|
52 |
@Override
|
53 |
public synchronized boolean add(E element) { |
54 |
int pos;
|
55 |
if ((pos = historyArray.indexOf(element)) != -1) { |
56 |
if (pos==0) { |
57 |
// already in the top of the queue
|
58 |
return false; |
59 |
} |
60 |
historyArray.remove(pos); |
61 |
} |
62 |
if (historyArray.size() == maxSize) {
|
63 |
historyArray.remove(maxSize-1);
|
64 |
} |
65 |
historyArray.add(0, element);
|
66 |
return true; |
67 |
} |
68 |
|
69 |
@Override
|
70 |
public int size() { |
71 |
return historyArray.size();
|
72 |
} |
73 |
|
74 |
@Override
|
75 |
public boolean isEmpty() { |
76 |
return historyArray.isEmpty();
|
77 |
} |
78 |
|
79 |
@Override
|
80 |
public boolean contains(Object o) { |
81 |
return historyArray.contains(o);
|
82 |
} |
83 |
|
84 |
@Override
|
85 |
public Iterator<E> iterator() { |
86 |
return historyArray.iterator();
|
87 |
} |
88 |
|
89 |
@Override
|
90 |
public List<E> toList() { |
91 |
return Collections.unmodifiableList(historyArray); |
92 |
} |
93 |
|
94 |
} |