문제를 풀어보자

JAVA) 자바의 정석 기초편 11-4 연습 문제(Comparator 정렬)

휴일이 2022. 10. 14. 15:40

Q)

다음에 제시된 BanNoAscending 클래스를 완성하여,

ArrayList에 담긴 Student 인스턴스들이

반(ban)과 번호(no)로 오름차순 정렬이 되게 하시오

(반이 같은 경우, 번호를 비교해서 정렬)

 

 

 

BanNoAscending 클래스

 

class BanNoAscending implements Comparator<Student> {
    //no이 오름차순으로 나와야하는데, ban이 같으면 ban오름차순->no오름차순 이어야 함
    @Override
    public int compare(Student s1, Student s2) {
//        int i = 0;
//        if(s1.ban==s2.ban) { //반이 같으면
//            i = s2.no-s1.no; //넘버 오름차순
//            return i;
//        } else { //반이 다르다?
//            i = s1.ban-s2.ban; //반 내림차순
//            return i;
//        }
//
        return s1.ban==s2.ban ? s2.no-s1.no : s1.ban-s2.ban;
        //삼항 연산자 하면 개꿀
    }

}

 

 

메인 클래스

 

public class Ex11_3 {
    public static void main(String[] args) {
        ArrayList list = new ArrayList();
        list.add(new Student("홍길동",2,5,100,100,100));
        list.add(new Student("남궁성",2,3,90,70,80));
        list.add(new Student("김자바",1,3,80,80,90));
        list.add(new Student("이자바",1,4,70,90,70));
        list.add(new Student("안자바",1,5,60,100,80));

        //list 정렬 조건에 new BanNoAscending() 추가
        Collections.sort(list, new BanNoAscending());
        Iterator it = list.iterator();


        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }
}

 

 

 

반 내림차순이 재미 없어서

반 오름차순으로도 해봤는데

이게 왜 되지???싶어서

(반이 같으면 번호만 비교했고,

반이 다르면 반만 비교했는데

왜 반도 오름차순, 번호도 오름차순이 되지?

반은 뒤죽박죽 나와야 하는 거 아닌가?)

 

 

Comparator은 두 객체를 비교해서

자리 바꿈을 하는 메소드라는 것을 알았기 때문에

직접 자리 바꿈을 해보았다 ^^

 

 

진짜 반, 번호 오름차순 정렬이 가능하더라구요~

 

 

머리가 나쁘면 몸이 고생한다 ^^

728x90