Can't use binary search with Object Arraylist?

1.2k views Asked by At

I tried using a binary search with an Arraylist and it gave me this message:

The method binarySearch(List>, T) in the type Collections is not applicable for the arguments (ArrayList, String)

Here's the code:

ArrayList <Object> a = new ArrayList <Object> ();
String date = JOptionPane.showInputDialog(null, "Please enter the date.")
int index = Collections.binarySearch(a, date);

The binary search should return the position of a specific date from an array (a) of several dates. What am I doing wrong?

3

There are 3 answers

2
Turing85 On

To perform a binary search, your Collection must be sorted. In order to sort something, this something needs to have a well-defined order. That is, what the Comparable<T> interface is for. Object does not implement Comparable<Object> and therefore a List of Object cannot be sorted (ther are no criteria to sort them). Please look at the API for mor details.

3
Louis Wasserman On

a should be a List<String>, not a List<Object>. Collections.binarySearch expects the list to contain the same type you are searching for, and the lowest type in common -- Object -- is not Comparable, so it cannot be used for a binary search.

0
AudioBubble On

Object does not implement Comaparable<Object>. You must provide Comparator<Object>.

    ArrayList <Object> a = new ArrayList<>();
    // add elements to a.
    Comparator<Object> comparator = (x, y) -> x.toString().compareTo(y.toString());
    Collections.sort(a, comparator);
    String date = JOptionPane.showInputDialog(null, "Please enter the date.")
    int index = Collections.binarySearch(a, date, comparator);

comparatoer in this code is only an example.