Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparator vs Apache BeanComparator

Consider a simple class:

class Employee {

String name;
int sal;

....//getters and setters
}

I can create a Comparator to sort on field name for example.

class EmpSortByName implements Comparator<Employee>{

 @Override
 public int compare(Employee e1, Employee e2){
  return e1.getName().compareTo(e2.getName());
 }
}

However, looking at apache commons BeanComparator, sorting can be achieved in following way:

BeanComparator bc = new BeanComparator("name");
Collections.sort(employeeList, bc);

Thus, by using BeanComparator, I can achieve sorting with minimal code. What are the trade offs between using Comparators and BeanComparators: in terms of performance, usage scenarios (multiple fields sort, other factors)?

I also understand that to use BeanComparator, the beanutils jar has to be imported.

like image 295
aces. Avatar asked Jul 11 '12 21:07

aces.


2 Answers

The BeanComparator uses reflection to access the name property and compare the two objects. Although reflection performance has improved, it's still not as fast as accessing a field directly. Whether this is important or not depends on how many times it's called in your application, and in which context.

Another problem is that, if you refactor the method and rename it to getLastName(), the code using BeanComparator will not be refactored, and the problem will go unnoticed until runtime (or unit testing time).

Frankly, implementing a comparator is so easy that I don't think using reflection is a good idea. The benefit of avoiding 4 lines of trivial code isn't sufficient to compensate for the performance and maintainability problems it causes.

like image 70
JB Nizet Avatar answered Oct 21 '22 12:10

JB Nizet


Also with beancomparator you can compare more that one attribute in easy way with compareTuple org.ujac.util.BeanComparator beanComparator = new org.ujac.util.BeanComparator(compareTuple); Collections.sort(List,beanComparator);

like image 36
Janith Avatar answered Oct 21 '22 10:10

Janith