Can't use binary search with Object Arraylist?

≯℡__Kan透↙ 提交于 2019-12-11 10:25:14

问题


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?


回答1:


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.




回答2:


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:


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.



来源:https://stackoverflow.com/questions/30743531/cant-use-binary-search-with-object-arraylist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!