Tips

Reverse Order in Comparator.compare()

알 수 없는 사용자 2008. 2. 25. 11:23

역순으로 정렬하고자 할 때, 다음과 같이 인자의 순서를 뒤집어서 비교할 수 있다.

public int compare(Employee e1, Employee e2) {
 return e2.hireDate().compareTo(e1.hireDate());
}

하지만 결코 다음과 같이 -를 붙여서 역순으로 정렬하면 안된다.

// Don't do this!!
return -r1.hireDate().compareTo(r2.hireDate());

왜냐하면 Integer.MIN_VALUE를 음수화한 값은 여전히 음수이기 때문이다.

Reference:
http://java.sun.com/docs/books/tutorial/collections/interfaces/order.html