Monday, October 10, 2011

Comparable & Comparator

When we add two objects in a collection that doesn't allow duplication as in Set, we have to override the Objet.equals() method as well as Object.hashCode() method. But now we want to make all objects in a List or array sortable, that's why we have to deal with two interfaces: Comparable and Comparator.

Comparable

Implements Comparable interface in the bean class to make the bean comparable:

public class SerializableBean implements Comparable {

private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public int compareTo(SerializableBean o) {
return name.compareTo(o.name);
}
}

Now we can sort the list or array containing the beans using:

Collections.sort(list);
Arrays.sort(arr);

We can also find an index of an object inside the collection using binary search tree after sorting it:

Collections.binarySearch(list, key);
Arrays.binarySearch(arr, key);

Comparator

Create a new class that implements Comparator interface:

public class CompareByName implements Comparator {

@Override
public int compare(SerializableBean bean1, SerializableBean bean2) {
return bean1.getName().compareTo(bean2.getName());
}

}

Now we can use it to sort a list or array:

Collections.sort(list, new CompareByName());
Arrays.sort(arr, new CompareByName());

We can also find an index of an object inside the collection using binary search tree after sorting it:

Collections.binarySearch(list, key, new CompareByName());
Arrays.binarySearch(arr, key, new CompareByName());

0 comments:

 

©2009 Stay the Same | by TNB