From c64d46d0d894f80967b79a13db440c39bd04547a Mon Sep 17 00:00:00 2001 From: "ray.j.greenwell" Date: Fri, 4 Dec 2009 20:35:10 +0000 Subject: [PATCH] Allow non-Comparable arrays to be searched using a Comparable key. Is this weird? Maybe. It violates the requirment that the Comparable relation is transitive, because the "other" object need not even be Comparable. java.util.Arrays.binarySearch() (added in 1.6) is documented as if it supports this behavior, but it does not. git-svn-id: https://samskivert.googlecode.com/svn/trunk@2661 6335cc39-0255-0410-8fd6-9bcaacd3b74c --- src/java/com/samskivert/util/ArrayUtil.java | 24 ++++++++++----------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/java/com/samskivert/util/ArrayUtil.java b/src/java/com/samskivert/util/ArrayUtil.java index 7c1791ac..58b9b117 100644 --- a/src/java/com/samskivert/util/ArrayUtil.java +++ b/src/java/com/samskivert/util/ArrayUtil.java @@ -350,32 +350,32 @@ public class ArrayUtil } /** - * Performs a binary search, attempting to locate the specified - * object. The array must be sorted for this to operate correctly and - * the contents of the array must all implement {@link Comparable} - * (and actually be comparable to one another). + * Performs a binary search, attempting to locate the element that compares as equal + * to the specified Comparable key. Note that the array elements can implement + * {@link Comparable} and the key can be of the same type, or the key can be a completely + * different class that can compare the element type. + * All comparisons will be called as key.compareTo(element). * - * @param array the array of {@link Comparable}s to be searched. + * @param array the array to be searched. * @param offset the index of the first element in the array to be considered. * @param length the number of elements including and following the * element at offset to consider when searching. - * @param key the object to be located. + * @param key the Comparable that will be used to search the elements of the array. * * @return the index of the object in question or * (-(insertion point) - 1) (always a negative * value) if the object was not found in the list. */ - public static > int binarySearch ( - T[] array, int offset, int length, T key) + public static int binarySearch ( + T[] array, int offset, int length, Comparable key) { int low = offset, high = offset+length-1; while (low <= high) { int mid = (low + high) >>> 1; - T midVal = array[mid]; - int cmp = midVal.compareTo(key); - if (cmp < 0) { + int cmp = key.compareTo(array[mid]); + if (cmp > 0) { low = mid + 1; - } else if (cmp > 0) { + } else if (cmp < 0) { high = mid - 1; } else { return mid; // key found