본문 바로가기
Java/API

[JAVA] Comparator

by TheUphill 2016. 2. 2.
Collection의 데이터들을 정렬하는데 사용된다. 

- Usage
두 값을 처리한 리턴 결과가 때 음수,0,양수 이냐에 따라 첫번째 인자의 정렬 순위가 낮음,값음,높음 으로 정의될 수 있다.
(Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.)

class ProductComparator implements Comparator<Product> {
    @Override
    public int compare(Product o1, Product o2) {
        if ( productSortOrder.equals(SORT_DESC) ) {
            // o1=1, o2=10일 경우 리턴 결과가 양수임으로 o1의 우선순위가 더 높다.(내림차순)
            return new Long(o2.getOrderNum() - o1.getOrderNum()).intValue();

        } else if ( productSortOrder.equals(SORT_ASC) ) {
            // o1=1, o2=10일 경우 리턴 결과가 음수임으로 o1의 우선순위가 더 낮다.(오름차순)
            return new Long(o1.getOrderNum() - o2.getOrderNum()).intValue();
        } else {
            return new Long(o1.getOrderNum() - o2.getOrderNum()).intValue();
        }
    }
}

String 정렬
//오름차순 order
return fruitName1.compareTo(fruitName2);

//내림차순 order
//return fruitName2.compareTo(fruitName1);


- 주의사항
 1. Comparator는 sorted map이나 sorted set과 함께 사용될 수 있는데, 이 때 특정 두 속성 a,b에 대해 Comparator.comapre(a,b)==0 != a.equals(b) 일 경우 위 collection의 형태가 기이해질 수 있다. 
The ordering imposed by a comparator c on a set of elements S is said to be consistent with equals if and only if c.compare(e1, e2)==0 has the same boolean value as e1.equals(e2) for every e1 and e2 in S.

Caution should be exercised when using a comparator capable of imposing an ordering inconsistent with equals to order a sorted set (or sorted map). Suppose a sorted set (or sorted map) with an explicit comparator c is used with elements (or keys) drawn from a set S. If the ordering imposed by c on S is inconsistent with equals, the sorted set (or sorted map) will behave "strangely." In particular the sorted set (or sorted map) will violate the general contract for set (or map), which is defined in terms of equals.

For example, suppose one adds two elements a and b such that (a.equals(b) && c.compare(a, b) != 0) to an empty TreeSet with comparator c. The second add operation will return true (and the size of the tree set will increase) because a and b are not equivalent from the tree set's perspective, even though this is contrary to the specification of the Set.add method.

참고


댓글