본문 바로가기

Algorithm/이론

Comparable & Comparator

728x90
반응형

 

Comparable

This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method.

Lists (and arrays) of objects that implement this interface can be sorted automatically by Collections.sort (and Arrays.sort). Objects that implement this interface can be used as keys in a sorted map or as elements in a sorted set, without the need to specify a comparator.

Comparable은 interface이고, 비교를 통해 "순서"를 정하는 정렬에 사용되며 compareTo() 메소드의 기능이 있다.

Comparable interface를 상속하는 List, array 객체들은 자동적으로 Collections.sort와 Arrays.sort를 통해 정렬할 수 있다.

메소드 설명
int compareTo(T o) 해당 객체와 전달된 객체의 순서를 비교함

 

import java.util.*;

public class Movie implements Comparable<Movie> {

	private int id;
	private String name;
	
	public Movie(int id, String name) {
		this.id=id;
		this.name=name;
	}
	
	public int getId() {
		return id;
	}
	
	public String getName() {
		return name;
	}
	
    //id 오름차순
	@Override
	public int compareTo(Movie m) {
		return this.id-m.id;
	}
	
    //id 내림차순
	@Override
	public int compareTo(Movie m) {
		return m.id-this.id;
	}
	
    //name 오름차순
	@Override
	public int compareTo(Movie m) {
		return this.name.compareTo(m.name);
	}
	
    //name 내림차순
	@Override
	public int compareTo(Movie m) {
		return m.name.compareTo(this.name);
	}
	
	
	
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		List<Movie> list = new ArrayList<>();
		list.add(new Movie(5,"KIM"));
		list.add(new Movie(3,"PAIK"));
		list.add(new Movie(1,"PARK"));
		list.add(new Movie(2,"SHIN"));
		list.add(new Movie(4,"WHANG"));
		
		Collections.sort(list);
		for(Movie movie : list) {
			System.out.println(movie.getId());
		}
	}
}

 

A.compareTo(B) 에서

A < B return -1;

A = B return 0;

A > B return 1;

 

compareTo에 따라서 Collections.sort(list)정렬 할 때, 오름차순과 내림차순을 정할 수 있다.

A < B(return -1)일 경우 오름차순이므로, 내림차순을 만들고 싶으면 A,B의 위치를 바꾸어서 A > B(return 1)로 만들어주어야 한다.

그러면 return에서 앞뒤 관계를 바꿔주면 된다.

 

Collections.sort(List<E>)이기 떄문에 sort()는 list 함수일 때만 가능하다. 따라서 ArrayList를 사용한다.

 

 

 

Comparator

A comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order.

Comparators can also be used to control the order of certain data structures (such as sorted sets or sorted maps), or to provide an ordering for collections of objects that don't have a natural ordering.

Comparator은 interface이고, 정렬순서를 좀 더 정확하고 구체적으로 할 수 있도록 돕는다. set,map 등 자료구조의 정렬에 사용되고 자연적으로 정렬 할 수 없는 객체들을 정렬 할 수 있다.

 

메소드 설명
int compare(T o1, T o2) 전달된 두 객체의 순서를 비교함

 

 

import java.util.*;

public class Movie {

	private int id;
	private String name;
	
	public Movie(int id, String name) {
		this.id=id;
		this.name=name;
	}
	
	public int getId() {
		return id;
	}
	
	public String getName() {
		return name;
	}
	
	static class sortById implements Comparator<Movie> {
		
		//id 오름차순
		@Override
		public int compare(Movie m1, Movie m2) {
			return m1.id-m2.id;
		}
		
		//id 내림차순
		@Override
		public int compare(Movie m1, Movie m2) {
			return m2.id-m1.id;
		}
	}
	
	static class sortByName implements Comparator<Movie> {
		
		//name 오름차순
		@Override
		public int compare(Movie m1, Movie m2) {
			return m1.name.compareTo(m2.name);
		}
		
		//name 내림차순
		@Override
		public int compare(Movie m1, Movie m2) {
			return m1.name.compareTo(m2.name);
		}
	}
	
	
	
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		List<Movie> list = new ArrayList<>();
		list.add(new Movie(5,"KIM"));
		list.add(new Movie(3,"PAIK"));
		list.add(new Movie(1,"PARK"));
		list.add(new Movie(2,"SHIN"));
		list.add(new Movie(4,"WHANG"));
		
		sortById sbi = new sortById();
		sortByName sby = new sortByName();
		
		Collections.sort(list, sby);
		for(Movie movie : list) {
			System.out.println(movie.getName());
		}
	}
}

 

compare(T o1, T o2)에서

o1 < o2 return -1;

o1 = o2 return 0;

o1 > o2 return 1;

 

Comparable과는 다르게 Comparator는 내가 원하는 정렬방식을 위해서 새로운 class에서 compare을 정의한다. 따라서 implements는 compare()를 구현한 새로운 class에 붙인다.

 

Comparable과 마찬가지로 o1 < o2(return -1)는 오름차순이기 때문에, 내림차순을 만들고 싶으면 o1,o2위치를 바꿔서 o1 > o2(return 1)를 만든다.

 

Collections.sort(list, sby); 로 내가 원하는 정렬방식의 객체를 list이름 뒤에 추가하면 동작한다. sbi, sby객체는 각각 id와 name을 기준으로 정렬을 수행하며 각각 객체를 만들어 구현했으므로 서로 영향을 주지 않고 사용할 수 있다.

 

 

Comparable Comparator
자연적 순서로 객체를 정렬 다양한 객체들의 특성을 정렬
"this"로 객체를 비교 클래스 서로 다른 2개의 객체를 비교
java.lang.pacakage java.util pacakage
원래의 클래스에 영향을 미칠 수 있어 변경이 가능 원래의 클래스의 아무런 영향을 미치지 않는다
compareTo() compare(),equals()

 

 

 

728x90
반응형

'Algorithm > 이론' 카테고리의 다른 글

다익스트라(dijkstra)  (0) 2020.07.13
PriorityQueue / Deque  (0) 2020.07.10
Set<E> vs Map<K,V>  (0) 2020.07.10
BufferedReader  (0) 2020.07.06
투 포인터(Two Pointer)  (0) 2020.07.05