compareTo()

소만이·2024년 3월 15일
post-thumbnail

compareTo(T other)

int 값으로 리턴하는 메서드이며 비교 대상 객체와 현재 객체를 비교해서 순서를 결정한다.
여기서 'T'는 비교할 대상 객체의 타입을 나타낸다. 이 메서드는 현재 객체가 비교 대상 객체보다 작으면
음수를, 같으면 0을, 크면 양수를 반환한다.


Date date1 = new Date();
Date date2 = new Date();

int result = date1.compareTo(date2);

if(result < 0){
	//date1이 date2보다 작다는 뜻 -> 이른 날짜라는 뜻
}else if(result == 0){
	//date1 과 date2가 같다는 뜻 -> 같은 날짜라는 뜻
}else{
	//date1이 date2보다 크다는 뜻 -> 늦은 날짜라는 뜻
}

이 compareTo()의 반환값을 가지고 Collections.sort() 메서드를 가지고 정렬할 수 가 있다.

public class IssueSorter {
    public static void sortByDate(List<Issue> issueList) {
        Collections.sort(issueList, new Comparator<Issue>() {
            @Override
            public int compare(Issue issue1, Issue issue2) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
                try {
                    Date date1 = dateFormat.parse(issue1.getFields().getCustomfield_11638());
                    Date date2 = dateFormat.parse(issue2.getFields().getCustomfield_11638());
                    return date1.compareTo(date2);
                } catch (ParseException e) {
                    e.printStackTrace();
                    return 0;
                }
            }
        });
    }
} 

Collections.sort()

리스트나 배열같은 컬렉션을 정렬하는데 사용된다.
위에 코드를 보면
Collections.sort(issueList, new Comparator<>(){});
이렇게 쓰인 부분이 있을 것이다. 리스트의 요소 클래스가 Comparable 인터페이스를 구현하고 있으면 단순히 sort(List<> list) 의 형태로 쓸 수 있겠지만 그렇지 않은 경우, Comparator객체를 전달하여 정렬 기준을 제공해야한다.

0개의 댓글