You can extends existing ArrayList
To create a SortedList
. As you will only have to take care of order while insertion.
public class SortedList<E extends Comparable<E>> extends ArrayList<E> {
@Override
public boolean add(E e) {
int index = Collections.binarySearch(this, e);
super.add(index < 0 ? ~index : index, e);
return true;
};
}
Java Doc Collections.binarySearch
Returns: the index of the search key, if it is contained in the list; otherwise, (-(insertion point) - 1)
. The insertion point is defined as the point at which the key would be inserted into the list: the index of the first element greater than the key, or list.size() if all elements in the list are less than the specified key. Note that this guarantees that the return value will be >= 0
if and only if the key is found.
Update:
As @Louis Wasserman has pointed out this create problems with basic list contract that is insert elements based on index. If you want to support that functionality then you should use Collections.sort()
. You can also use org.apache.commons.collections.list.TreeList
which has below relative performance statistics to that class
get add insert iterate remove
TreeList 3 5 1 2 1
ArrayList 1 1 40 1 40
LinkedList 5800 1 350 2 325