Question

i am new to java and encountering a problem with Collections.binarySearch, i have raed the javadoc and check lots of answers in here, but still dealing with a problem. before the actual code, a background: i am writing a code that lets the user manage a contact book. this is my Contact class

public class Contact implements Comparable<Contact>  {
private String name;
private String email;
private String phone;
private String address;

i have a comparator

public int compareTo(Contact contact) {  
    return name.compareToIgnoreCase(contact.getName());  
}

also inside the class, and i have a different class for the copmare itself

public class ContactComparator implements Comparator<Contact> {
@Override
public int compare(Contact first, Contact second) {
  String one = first.getName();
  String two = second.getName();
  int f = one.compareToIgnoreCase(two);
  return f;
}

}

in the code i've sort my list all the time, like someone here helped me before

Collections.sort(contacts , new ContactComparator())

now my problem is that im trying to use binary search in a search method that goes like:

public int ContactIndex(final String name){
    return Collections.binarySearch(contacts, name, new ContactComparator());  
}

but it gives me this error:

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

i need your help again guys, thank you all helpers!!!

Was it helpful?

Solution

You should send a Contact as argument that contains the name of the desired contact to search instead of sending just a String. Note that your ContactComparator compares Contacts not Contact and String.

The code would look like this:

public int ContactIndex(final String name) {
    Contact contactToSearch = new Contact();
    contactToSearch.setName(name);
    return Collections.binarySearch(contacts, contactToSearch, new ContactComparator());  
}

OTHER TIPS

Method signature is

public static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c)

Your T is String. So your List must contain a subclass of String. Same goes with the Comparator. Now your Contact class does not extend String.. so you are getting the error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top