본문으로 바로가기

[Java] Comparable vs Comparator

category TIL/Java 2022. 4. 28. 01:27

Comparable

정렬 수행 시 기본적으로 적용되는 정렬 기준이 되는 메서드를 정의하는 인터페이스
  • package: java.lang.Comparable
  • Java에서 제공되는 정렬이 가능한 모든 클래스들이 구현

구현

  • implements Comparable<객체 타입>
  • public int compareTo(객체 타입 o)
  • 오름차순 → 현재 객체 - 파라미터 객체
  • 내림차순 → 파라미터 객체 - 현재 객체

사용

  • Arrays.sort(___)
  • Collections.sort(___)

↓ Arrays.sort() vs Collections.sort()

더보기

Arrays.sort()

- 배열을 정렬할 경우

Collections.sort()

- ArrayList, LinkedList, Vector 등을 정렬할 경우

 

예시

class Main {

    class Point implements Comparable<Point> {
        int row, column;

        Point(int row, int column) {
            this.row = row;
            this.column = column;
        }

        public int compareTo(Point o) {
            if(this.row == o.row) return this.column - o.column;
            else return this.row - o.column;
        }
    }


    public static void main(String[] args) {
        ArrayList<Point> list = new ArrayList<>();
        Collections.sort(list);
    }
}

 

Comparator

정렬 가능한 클래스들의 기본 정렬 기준과 다르게 정렬할 때 사용하는 인터페이스
  • package: java.util.Comparator
  • 내림차순 정렬할 때 많이 사용

구현

  • implements Comparator<객체 타입>
  • public int compare(객체 타입 o1, 객체 타입 o2)
  • 오름차순 → 파라미터 객체1 - 파라미터 객체2
  • 내림차순 → 파라미터 객체2 - 파라미터 객체1

사용

  • Arrays.sort(___)
  • Collections.sort(___)

 

예시

class Point {
	int row, column;
    
	Point(int row, int column) {
		this.row = row;
		this.column = column;
	}
}



class ComparatorImpl implements Comparator<Point> {
	public int compare(Point o1, Point o2) {
		if(o1.row == o2.row) return o1.column - o2.column;
		else return o1.row - o2.column;
	}
}



class Main {
	public static void main(String[] args) {
		ArrayList<Point> list = new ArrayList<>();
		ComparatorImpl comparatorImpl = new ComparatorImpl();

	}
}
class Main {

	class Point {
		int row, column;

		Point(int row, int column) {
			this.row = row;
			this.column = column;
		}
	}


	public static void main(String[] args) {
		PriorityQueue<Point> pq = new PriorityQueue<>(new Comparator<Point>() {
			public int compare(Point o1, Point o2) {
				if(o1.row == o2.row) return o1.column - o2.column;
				else return o1.row - o2.column;
			}
		});
	}
}

 


 

[ 출처 ]

https://gmlwjd9405.github.io/2018/09/06/java-comparable-and-comparator.html