Search code examples
javabinary-search

ArrayList BinarySearch


question

I want to implement a BinarySearch method myself on an Object of Klant how do i do this? Klant has some variables.

public class Klant {
public String klantID;
private String voornaam;
private String tussenvoegsel;
private String achternaam;
private int leeftijd;
private static boolean MAN = true;
private String plaats;
private String email;
/*
 *  Getters and setters included 
 */
}

Klant toevoeging = new Klant("FirstName", "middleName", "\Lastname\"", 20, false, "Location", "email@email.com");
klanten.add(toevoeging);

Solution

  • Using Collections.binarySearch(...)

    When you run a Collections.binarySearch(...); on a list the objects in that list must either implement Comparable, or you will have to pass a Comparator into the binarySearch(...) method;

    Using a Comparator as an example you could do the following;

    class KlantComparator implements Comparator<Klant> {
        @Override
        public int compare(Klant o1, Klant o2) {
            if(condition)
              return 1;
            else if(condition2)
              return 0;
            else 
              return -1;
        }
    }
    

    In the above you compare the Klant objects o1 and o2 and return 1 if o1 should be ranked higher than o2, return 0 if they are the same, and return -1 if o1 is ranked lower than o2. And then to run the binary search;

        KlantComparator kc = new KlantComparator();
        ArrayList klants = new ArrayList<Klant>();
        Klant o = new Klant();
        klants.add(o);
        klants.add(new Klant());
        klants.add(new Klant());
        Collections.sort(klants, kc);
        Collections.binarySearch(klants, o, kc);
    

    In the above please note that the klants collection needs to be sorted first, and that the binarySearch needs to be performed using the same Comparator that sorted the list.

    I hope this helps.

    Further Reading;