2

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?

Vctrm6
  • 31
  • 1
  • 7

3 Answers3

3

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.

Turing85
  • 18,217
  • 7
  • 33
  • 58
  • k thanks. The problem is, my array is going to contain both doubles and strings, so how would I go about searching the array for a specific string among doubles and strings? – Vctrm6 Jun 09 '15 at 22:05
  • 1
    @Vctrm6 you mean your `ArrayList`, right? I think your algorithm is broken by design. Either store the `double`s as Strings in your `ArrayList` and re-parse them into doubles (dirty work-around) or overthink your design, so you do not need to store `String`s and `double`s in the same list. – Turing85 Jun 09 '15 at 22:09
2

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.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • Ok thanks. The problem is, my array is going to contain both doubles and strings, so how would I go about searching the array for a specific string among doubles and strings? – Vctrm6 Jun 09 '15 at 22:05
  • 2
    You can't use `binarySearch`, then. You could use `indexOf`, and accept that it'll take O(n). (But frankly, mixing two different types in the same list like that is a huge design smell that says you're doing something deeply wrong.) – Louis Wasserman Jun 09 '15 at 22:06
  • @Vctrm6 you could have posted this as comment under your question instead of asking both of us the same. Anyway, you got the same basic answer: bad design. – Turing85 Jun 09 '15 at 22:12
0

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.