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:
Post a Comment