Tuesday 17 June 2014

Another way to read an object in ArrayList or Array by binary search without sort


Java programmers use ArrayList and Array a lot including me. It could be a pain to retrieve the objects stored in side by the member values instead of position index. Collections.sort() has to be called before binary search. If we want to keep the original order unchanged, then this approach cannot be used.

Fortunately, we can use TreeMap to store the object as key and the index of Array as value. For this purpose, the objects in Array must be Comparable or a customized comparator must be created for the class of them.

E.g.,

ArrayList al = new ArrayList();
//Populate al by fetching Database records here...
TreeMap tm = new TreeMap(new StudentAgeComparator());
For (int i = 0; i< al.size(); i ++) {
   tm.put((Student) al.get(i), i);
}

public class StudentAgeComparator implements Comparator {
   @Override
   public int compare(Student stu1, Student stu2) {
      if (stu1.getAge() > Stu2.getAge()) return 1;
      if (stu1.getAge() < Stu2.getAge()) return -1;
      return 0;
   }
}

pulic class Student {
  private Integer id;
  private String name;
  private Date dob;

  public Float getAge() {
      return  (Float)(new Date().getTime() - dob.getTime()) / (1000*60*60*24l));
  }
  //......
}


Then we can use TreeMap search function to get the index in ArrayList. In this way, we can keep the order of student in ArrayList by ID for other processing and use the TreeMap just like a database index for a table.

No comments: