2 Replies Latest reply: Jan 14, 2011 10:31 AM by aksarben RSS

    Searching Sorted List

    aksarben
      I'm trying to write a method that searches a sorted list using compareTo() rather than equals(), as follows:
      public static <T extends Comparable<T>> T find(final T instance, final List<T> list) {
      
         T result = null;
         for (final T entry : list) {
            final int comparison = entry.compareTo(instance);
           if (comparison < 0) {
              continue;
              }
              if (comparison > 0) {
                 break;
              }
           result = entry;
           break;
         }
         return result;
      }
      I have two classes, A & B:
      Class A implements Comparable<A>
      ...
      Class B extends A
      I don't understand why this won't compile:
      List<B> list;
      B item;
      ...
      final B result = find(item, list);
      The error message reads like this:
      Bound mismatch: The generic method find(T, List<T>) ... is not applicable for the arguments (B, List<B>).
      The inferred type B is not a valid substitute for the bounded parameter <T extends Comparable<T>>
      Is this just a syntax error on my part, or is not possible to do what I'm attempting? Or is there a standard Collections class that already does this? I looked at Collections.binarySearch(), but I need to use compareTo() rather than equals() to determine a match.