자바 프로그래밍을 하다보면 객체를 정렬해야 할 경우가 자주 있다.

ex) 학생들을 국어 점수를 감소하는 순, 좌표를 x좌표가 증가하는 순 등..

 

객체의 정렬 기준을 명시하는 방법에는 두 가지가 있다.

1. Interface Comparable

2. Interface Comparator

 

 

 

1. Comparable 

정렬 수행 시 기본적으로 적용되는 정렬 기준이 되는 메서드를 정의하는 인터페이스

 

> 구현 방법

정렬할 객체에 Comparable interface를 implements 후, compareTo() 메서드를 오버라이드하여 구현한다.


compareTo() 메서드 작성법 - 리턴 값이 0이나 음수면 기준값은 고정, 양수 값이면 바뀐다.

  1. 현재 객체 < 파라미터로 넘어온 객체: 음수 리턴

  2. 현재 객체 == 파라미터로 넘어온 객체: 0 리턴

  3. 현재 객체 > 파라미터로 넘어온 객체: 양수 리턴

 

 

Comparable Example


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class compa {
	public static void main(String[] args) {
		int x = 3, y = 4;
		List arrList = new ArrayList<>();
		arrList.add(new Point(x, y));
		x=1; y=1;
		arrList.add(new Point(x, y));
		Collections.sort(arrList);
		x=4; y= 7;
		arrList.add(new Point(x, y));
		for(int i=0; i<arrList.size(); i++) {
			System.out.println(arrList.get(i).x +" "+arrList.get(i).y);
		}
	}
	// x좌표가 증가하는 순, x좌표가 같으면 y좌표가 감소하는 순으로 정렬하라.
	static class Point implements Comparable {
	    int x, y;
	    
	    public Point(int x,int y) {
	    		this.x=x;
	    		this.y=y;
	    }
	    @Override
	    public int compareTo(Point p) {
	        if(this.x > p.x) {
	            return 1; // x에 대해서는 오름차순
	        }
	        else if(this.x == p.x) { // 같을경우에
	            if(this.y < p.y) { // y에 대해서는 내림차순
	                return 1;
	            }
	        }
	        return -1;
	    }
	}

}

 

 

2. Comparator

정렬 가능한 클래스(Comparable 인터페이스를 구현한 클래스)들의 기본 정렬 기준과 다르게 정렬 하고 싶을 때 사용하는 인터페이스

 

compare() 메서드 작성법 - 리턴 값이 0이나 음수면 기준값은 고정, 양수 값이면 바뀐다.

  1. 현재 객체 < 파라미터로 넘어온 객체: 음수 리턴

  2. 현재 객체 == 파라미터로 넘어온 객체: 0 리턴

  3. 현재 객체 > 파라미터로 넘어온 객체: 양수 리턴

Comparator Example


 	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int N = Integer.parseInt(br.readLine());
		ArrayList arrList = new ArrayList<>();
		StringTokenizer st;
		for(int i=0; i tmp = new ArrayList<>();
        ....
        Collections.sort(tmp, new point_compartor());
	}
	public static class Point implements Comparable{
		int x;
		int y;
		public Point(int x,int y) {
			this.x=x;
			this.y=y;
		}
		@Override
		public int compareTo(Point o) {
			int val = this.x - o.x;
			if(val == 0) {
				return this.y-o.y;
			}else
				return val;
		}
	}
	
	public static class point_compartor implements Comparator{

		@Override
		public int compare(Point o1, Point o2) {
			// TODO Auto-generated method stub
			return o1.y-o2.y;
		}
	}
    
   

+ Recent posts