Tuesday, September 20, 2011

Binary Search in a List of Objects

Search a value from list of object by using binary search.

There is an employee class where, we need to find out the employee details by passing employee name.

Created a EmpTest.java class.
Used interface Comparable, to sort through employee name.

public class EmpTest implements Comparable<EmpTest> {
private int id;
private String name;
private String age;

public EmpTest() {

public EmpTest(int id, String name, String age) {
this.age = age;
this.id = id;
this.name = name;

// setters and getters

public int compareTo(EmpTest emp)
return this.name.compareTo(emp.getName());

Creating ListTest.java class, where created employee details and added into the list.
before performing binary search, sort the list values.
If the corresponding search value is not found, while using binary search, it throws java.lang.ArrayIndexOutOfBoundsException.

public class ListTest {

public static void main(String[] args) {

List<EmpTest> listValues = new ArrayList<EmpTest>();

listValues.add(new EmpTest(1, "Test1", "23"));
listValues.add(new EmpTest(6, "Test6", "28"));
listValues.add(new EmpTest(2, "Test2", "24"));
listValues.add(new EmpTest(5, "Test5", "27"));
listValues.add(new EmpTest(3, "Test3", "25"));


EmpTest empTest = listValues.get(Collections.binarySearch(
listValues, new EmpTest(0, "Test6", null)));
System.out.println("Emp Name : " + empTest.getName() + ", Age : "
+ empTest.getAge());
catch (ArrayIndexOutOfBoundsException e)
System.out.println("Employee Name is not Existing!!!");


No comments :

Post a Comment