Java

Comparator와 Comparable

나는 나야 2024. 5. 20. 13:38

이전 포스트에서 질문이 있어, 새롭게 글을 작성하게 되었습니다.

 

우선, Comparable은 '비교할 수 있는 ~Class'라는 뜻이 될 것이고, Comparator는 '비교자'라는 뜻이 될 것 입니다.

Time이라는 Class는 시간과 관련하여 역할을 갖고 있는 주체입니다.

따라서 Time이 갖고 있는 비교 인터페이스는 Comparable이 더 어울리지 않나 생각이 듭니다.

// 물론 이것과 다른 의견이 있으신 분들은 환영입니다!!!

 

우선 TreeSet을 통해 구현해보겠습니다.

 

Comparator를 통한 비교

import java.util.Comparator;
import java.util.TreeSet;

public class ComparableTime {
    private static class Time implements Comparable<Time>{
        int hour;
        int minutes;

        public Time(int hour, int minutes) {
            this.hour = hour;
            this.minutes = minutes;
        }

        @Override
        public String toString() {
            return "Time{" +
                    "hour=" + hour +
                    ", minutes=" + minutes +
                    '}';
        }

        @Override
        public int compareTo(Time time) {
            return Integer.compare(this.hour, time.hour);
        }
    }
    public static void main(String[] args) {
        TreeSet<Time> tree = new TreeSet<>();
        tree.add(new Time(1, 10));
        tree.add(new Time(2, 10));
        tree.add(new Time(8, 10));
        tree.add(new Time(4, 10));
        tree.add(new Time(12, 10));

        System.out.println("tree = " + tree);
    }
}

 

Comparable를 통한 비교

import java.util.Comparator;
import java.util.TreeSet;

public class ComparatorTime {
    private static class HourComparator implements Comparator<Time> {

        @Override
        public int compare(Time o1, Time o2) {
            return Integer.compare(o1.hour, o2.hour);
        }
    }

    private static class Time {
        int hour;
        int minutes;

        public Time(int hour, int minutes) {
            this.hour = hour;
            this.minutes = minutes;
        }

        @Override
        public String toString() {
            return "Time{" +
                    "hour=" + hour +
                    ", minutes=" + minutes +
                    '}';
        }
    }
    public static void main(String[] args) {
        TreeSet<Time> tree = new TreeSet<>(new HourComparator());
        tree.add(new Time(1, 10));
        tree.add(new Time(2, 10));
        tree.add(new Time(8, 10));
        tree.add(new Time(4, 10));
        tree.add(new Time(12, 10));

        System.out.println("tree = " + tree);
    }
}

 

 

TreeSet에 바로 비교를 나타내는 경우도 3가지가 있습니다.

 

import java.util.Comparator;
import java.util.TreeSet;

public class ComparableSelf {
    private static class Time {
        int hour;
        int minutes;

        public Time(int hour, int minutes) {
            this.hour = hour;
            this.minutes = minutes;
        }

        @Override
        public String toString() {
            return "Time{" +
                    "hour=" + hour +
                    ", minutes=" + minutes +
                    '}';
        }
    }
    public static void main(String[] args) {
        TreeSet<Time> tree = new TreeSet<>(new Comparator<Time>() {
            @Override
            public int compare(Time o1, Time o2) {
                return Integer.compare(o1.hour, o2.hour);
            }
        });

        TreeSet<Time> tree1 = new TreeSet<>((o1, o2) -> Integer.compare(o1.hour, o2.hour));

        TreeSet<Time> tree2 = new TreeSet<>(Comparator.comparingInt(o -> o.hour));

        tree.add(new Time(1, 10));
        tree.add(new Time(2, 10));
        tree.add(new Time(8, 10));
        tree.add(new Time(4, 10));
        tree.add(new Time(12, 10));

        tree1.add(new Time(1, 10));
        tree1.add(new Time(2, 10));
        tree1.add(new Time(8, 10));
        tree1.add(new Time(4, 10));
        tree1.add(new Time(12, 10));

        tree2.add(new Time(1, 10));
        tree2.add(new Time(2, 10));
        tree2.add(new Time(8, 10));
        tree2.add(new Time(4, 10));
        tree2.add(new Time(12, 10));

        System.out.println("tree = " + tree);
        System.out.println("tree1 = " + tree1);
        System.out.println("tree2 = " + tree2);
    }
}

 

 

역시 결과는 똑같이 나오는 것을 확인할 수 있습니다.

tree = [Time{hour=1, minutes=10}, Time{hour=2, minutes=10}, Time{hour=4, minutes=10}, Time{hour=8, minutes=10}, Time{hour=12, minutes=10}]
tree1 = [Time{hour=1, minutes=10}, Time{hour=2, minutes=10}, Time{hour=4, minutes=10}, Time{hour=8, minutes=10}, Time{hour=12, minutes=10}]
tree2 = [Time{hour=1, minutes=10}, Time{hour=2, minutes=10}, Time{hour=4, minutes=10}, Time{hour=8, minutes=10}, Time{hour=12, minutes=10}]

 

 

이러한 정렬에 대해서 한번 더 정리할 수 있는 시간이 되었으면 좋겠습니다! 

 

모두다 즐거운 코딩하시길 바랍니다! 😊👍

'Java' 카테고리의 다른 글

자바의 정렬의 모든 것  (2) 2024.05.19
Arrays.copyOf가 왜 빠를까  (0) 2024.05.10