01: /**
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing, software
12: * distributed under the License is distributed on an "AS IS" BASIS,
13: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: * See the License for the specific language governing permissions and
15: * limitations under the License.
16: */package org.apache.solr.util;
17:
18: import java.util.*;
19:
20: /**
21: * A TreeSet that ensures it never grows beyond a max size.
22: * <code>last()</code> is removed if the <code>size()</code>
23: * get's bigger then <code>getMaxSize()</code>
24: */
25: public class BoundedTreeSet<E> extends TreeSet<E> {
26: private int maxSize = Integer.MAX_VALUE;
27:
28: public BoundedTreeSet(int maxSize) {
29: super ();
30: this .setMaxSize(maxSize);
31: }
32:
33: public BoundedTreeSet(int maxSize, Collection<? extends E> c) {
34: super (c);
35: this .setMaxSize(maxSize);
36: }
37:
38: public BoundedTreeSet(int maxSize, Comparator<? super E> c) {
39: super (c);
40: this .setMaxSize(maxSize);
41: }
42:
43: public BoundedTreeSet(int maxSize, SortedSet<E> s) {
44: super (s);
45: this .setMaxSize(maxSize);
46: }
47:
48: public int getMaxSize() {
49: return maxSize;
50: }
51:
52: public void setMaxSize(int max) {
53: maxSize = max;
54: adjust();
55: }
56:
57: private void adjust() {
58: while (maxSize < size()) {
59: remove(last());
60: }
61: }
62:
63: public boolean add(E item) {
64: boolean out = super .add(item);
65: adjust();
66: return out;
67: }
68:
69: public boolean addAll(Collection<? extends E> c) {
70: boolean out = super.addAll(c);
71: adjust();
72: return out;
73: }
74: }
|