1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.springframework.osgi.service.importer.support.internal.collection;
18
19 import java.util.Collection;
20 import java.util.Collections;
21 import java.util.Comparator;
22
23 import org.springframework.util.Assert;
24
25 /**
26 * A specilized subtype of DynamicList which impose an order between its
27 * elements.
28 *
29 * @author Costin Leau
30 *
31 */
32 public class DynamicSortedList extends DynamicList {
33
34 private final Comparator comparator;
35
36
37 public DynamicSortedList() {
38 this((Comparator) null);
39 }
40
41 public DynamicSortedList(Comparator c) {
42 super();
43 this.comparator = c;
44
45 }
46
47 public DynamicSortedList(Collection c) {
48 this.comparator = null;
49 addAll(c);
50 }
51
52 public DynamicSortedList(int size) {
53 super(size);
54 this.comparator = null;
55 }
56
57
58
59 public boolean add(Object o) {
60 Assert.notNull(o);
61
62 if (comparator == null && !(o instanceof Comparable))
63 throw new ClassCastException("given object does not implement " + Comparable.class.getName()
64 + " and no Comparator is set on the collection");
65
66 int index = 0;
67
68 synchronized (storage) {
69 index = Collections.binarySearch(storage, o, comparator);
70
71 boolean duplicate = (index >= 0);
72
73
74
75 if (duplicate) {
76 boolean stillEqual = true;
77 while (index + 1 < storage.size() && stillEqual) {
78
79 stillEqual = false;
80 Object next = storage.get(index + 1);
81
82 if ((comparator != null ? comparator.compare(o, next) == 0 : ((Comparable) o).compareTo(next) == 0)) {
83 stillEqual = true;
84 index++;
85 }
86 }
87 }
88
89
90 else
91 index = -index - 1;
92
93 if (duplicate)
94 super.add(index + 1, o);
95 else
96 super.add(index, o);
97 }
98 return true;
99 }
100
101
102
103
104
105 public void add(int index, Object o) {
106 throw new UnsupportedOperationException("This is a sorted list; it is illegal to specify the element position");
107 }
108
109 public boolean addAll(int index, Collection c) {
110 throw new UnsupportedOperationException("This is a sorted list; it is illegal to specify the element position");
111 }
112
113 public Object set(int index, Object o) {
114 throw new UnsupportedOperationException("This is a sorted list; it is illegal to specify the element position");
115 }
116
117 }