Minimalistic Solution
Here is a "minimal" solution.
class SortedArrayList<T> extends ArrayList<T> {
@SuppressWarnings("unchecked")
public void insertSorted(T value) {
add(value);
Comparable<T> cmp = (Comparable<T>) value;
for (int i = size()-1; i > 0 && cmp.compareTo(get(i-1)) < 0; i--)
Collections.swap(this, i, i-1);
}
}
The insert runs in linear time, but that would be what you would get using an ArrayList anyway (all elements to the right of the inserted element would have to be shifted one way or another).
Inserting something non-comparable results in a ClassCastException. (This is the approach taken by PriorityQueue
as well: A priority queue relying on natural ordering also does not permit insertion of non-comparable objects (doing so may result in ClassCastException).)
Overriding List.add
Note that overriding List.add
(or List.addAll
for that matter) to insert elements in a sorted fashion would be a direct violation of the interface specification. What you could do, is to override this method to throw an UnsupportedOperationException
.
From the docs of List.add
:
boolean add(E e)
Appends the specified element to the end of this list (optional operation).
Same reasoning applies for both versions of add
, both versions of addAll
and set
. (All of which are optional operations according to the list interface.)
Some tests
SortedArrayList<String> test = new SortedArrayList<String>();
test.insertSorted("ddd"); System.out.println(test);
test.insertSorted("aaa"); System.out.println(test);
test.insertSorted("ccc"); System.out.println(test);
test.insertSorted("bbb"); System.out.println(test);
test.insertSorted("eee"); System.out.println(test);
....prints:
[ddd]
[aaa, ddd]
[aaa, ccc, ddd]
[aaa, bbb, ccc, ddd]
[aaa, bbb, ccc, ddd, eee]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…