@SuppressWarnings("unchecked") public static <T>int binarySearch(List<? extends T> list,T object,Comparator<? super T> comparator){
  if (comparator == null) {
    return Collections.binarySearch((List<? extends java.lang.Comparable<? super T>>)list,object);
  }
  if (!(list instanceof RandomAccess)) {
    ListIterator<? extends T> it=list.listIterator();
    while (it.hasNext()) {
      int result;
      if ((result=-comparator.compare(it.next(),object)) <= 0) {
        if (result == 0) {
          return it.previousIndex();
        }
        return -it.previousIndex() - 1;
      }
    }
    return -list.size() - 1;
  }
  int low=0, mid=list.size(), high=mid - 1, result=-1;
  while (low <= high) {
    mid=(low + high) >> 1;
    if ((result=-comparator.compare(list.get(mid),object)) > 0) {
      low=mid + 1;
    }
 else     if (result == 0) {
      return mid;
    }
 else {
      high=mid - 1;
    }
  }
  return -mid - (result < 0 ? 1 : 2);
}

@ SuppressWarnings ( "unchecked" ) public static < T > int binarySearch ( List < ? extends T > list , T object , Comparator < ? super T > comparator ) { if ( comparator == null ) { return Collections . binarySearch ( ( List < ? extends java . lang . Comparable < ? super T > > ) list , object ) ; } if ( ! ( list instanceof RandomAccess ) ) { ListIterator < ? extends T > it = list . listIterator ( ) ; while ( it . hasNext ( ) ) { int result ; if ( ( result = - comparator . compare ( it . next ( ) , object ) ) <= 0 ) { if ( result == 0 ) { return it . previousIndex ( ) ; } return - it . previousIndex ( ) - 1 ; } } return - list . size ( ) - 1 ; } int low = 0 , mid = list . size ( ) , high = mid - 1 , result = - 1 ; while ( low <= high ) { mid = ( low + high ) > > 1 ; if ( ( result = - comparator . compare ( list . get ( mid ) , object ) ) > 0 ) { low = mid + 1 ; } else if ( result == 0 ) { return mid ; } else { high = mid - 1 ; } } return - mid - ( result < 0 ? 1 : 2 ) ; }
performs a binary search for the specified element in the specified sorted list using the specified comparator . the list needs to be already sorted according to the comparator passed . searching in an unsorted array has an undefined result . it ' s also undefined which element is found if there are multiple occurrences of the same element .
