From 8ddea694d399cf499dd873fddc1ce281628f6c58 Mon Sep 17 00:00:00 2001 From: mdb Date: Fri, 20 Sep 2002 21:28:08 +0000 Subject: [PATCH] Added insertSorted(). git-svn-id: https://samskivert.googlecode.com/svn/trunk@838 6335cc39-0255-0410-8fd6-9bcaacd3b74c --- .../samskivert/util/SortableArrayList.java | 38 ++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/projects/samskivert/src/java/com/samskivert/util/SortableArrayList.java b/projects/samskivert/src/java/com/samskivert/util/SortableArrayList.java index 3a6a1724..7d0c599b 100644 --- a/projects/samskivert/src/java/com/samskivert/util/SortableArrayList.java +++ b/projects/samskivert/src/java/com/samskivert/util/SortableArrayList.java @@ -1,5 +1,5 @@ // -// $Id: SortableArrayList.java,v 1.5 2002/08/12 01:10:32 mdb Exp $ +// $Id: SortableArrayList.java,v 1.6 2002/09/20 21:28:08 mdb Exp $ // // samskivert library - useful routines for java programs // Copyright (C) 2001 Michael Bayne @@ -67,6 +67,42 @@ public class SortableArrayList extends AbstractList } } + /** + * Inserts the specified item into the list into a position that + * preserves the sorting of the list. The list must be sorted prior to + * the call to this method (an empty list built up entirely via calls + * to {@link #insertSorted} will be properly sorted). The list must be + * entirely comprised of elements that implement {@link Comparable} + * and the element being added must implement {@link Comparable} as + * well. + * + * @return the index at which the element was inserted. + */ + public int insertSorted (Object value) + { + return insertSorted(value, Comparators.COMPARABLE); + } + + /** + * Inserts the specified item into the list into a position that + * preserves the sorting of the list according to the supplied {@link + * Comparator}. The list must be sorted (via the supplied comparator) + * prior to the call to this method (an empty list built up entirely + * via calls to {@link #insertSorted} will be properly sorted). + * + * @return the index at which the element was inserted. + */ + public int insertSorted (Object value, Comparator comp) + { + int ipos = binarySearch(value, comp); + if (ipos < 0) { + ipos = -(ipos+1); + } + _elements = ListUtil.insert(_elements, ipos, value); + _size++; + return ipos; + } + /** * Performs a binary search, attempting to locate the specified * object. The array must be sorted for this to operate correctly and