01: /*
02: * FixedSizeList.java
03: *
04: * This file is part of SQL Workbench/J, http://www.sql-workbench.net
05: *
06: * Copyright 2002-2008, Thomas Kellerer
07: * No part of this code maybe reused without the permission of the author
08: *
09: * To contact the author please send an email to: support@sql-workbench.net
10: *
11: */
12: package workbench.util;
13:
14: import java.util.Collections;
15: import java.util.Iterator;
16: import java.util.LinkedList;
17: import java.util.List;
18:
19: /**
20: * @author support@sql-workbench.net
21: */
22: public class FixedSizeList<T> {
23: private LinkedList<T> entries;
24: private int maxSize;
25:
26: public FixedSizeList() {
27: this (25);
28: }
29:
30: public FixedSizeList(int max) {
31: this .maxSize = max;
32: this .entries = new LinkedList<T>();
33: }
34:
35: /**
36: * Append an entry at the end of the list, without
37: * checking for duplicates or removing entries
38: * that exceed the max size. This should be used
39: * to initially fill the list.
40: */
41: public synchronized void append(T entry) {
42: if (entry == null)
43: return;
44: entries.add(entry);
45: }
46:
47: public synchronized int addEntry(T entry) {
48: if (entry == null)
49: return -1;
50:
51: // Don't allow duplicates
52: if (entries.contains(entry)) {
53: entries.remove(entry);
54: }
55: entries.addFirst(entry);
56: while (entries.size() > maxSize) {
57: entries.removeLast();
58: }
59: return entries.size();
60: }
61:
62: public synchronized int size() {
63: return entries.size();
64: }
65:
66: public synchronized T getFirst() {
67: return entries.getFirst();
68: }
69:
70: public Iterator iterator() {
71: return entries.iterator();
72: }
73:
74: public synchronized String toString() {
75: StringBuilder result = new StringBuilder(entries.size() * 80);
76: Iterator<T> itr = entries.iterator();
77: while (itr.hasNext()) {
78: result.append(itr.next().toString());
79: if (itr.hasNext())
80: result.append(',');
81: }
82: return result.toString();
83: }
84:
85: public synchronized List<T> getEntries() {
86: return Collections.unmodifiableList(this.entries);
87: }
88:
89: }
|