본문 바로가기

old/Programming

자바 comparable 사용법

반응형

계층구조

package: java.lang.Comparable

정의

compareTo 메서드를 사용해서 하나의 조건을 가진 정렬을 구현하기 위한 인터페이스.
예를 들어, 사이즈별로 오름차순으로 정렬을 쉽게 구현이 가능함.

compareTo() 메서드에 대하여

compareTo 메서드는 양수가 나오면 두 피라미터의 위치를 바꾸며, 그외에는 아무것도 하지 않습니다.

조건식 리턴값
첫번째 피라미터 < 두번째 피라미터 음수
첫번째 피라미터 == 두번째 피라미터 0
첫번째 피라미터 > 두번째 피라미터 양수

사용법

customObject implements Comparable<>

Arrays.sort(customObject);
Collections.sort(customObject);

Java 예제


import java.lang.Comparable;

public class customPoint implements Comparable<customPoint> {

    private int x = 0;
    private int y = 0;

    public customPoint(int x, int y) {
        this.x = x;
        this.y = y;

    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    @Override
    public int compareTo(customPoint p2) {
        if (this.y > p2.y) {
            return 1; // y is in ascending order
        }
        return -1;
    }
}

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

public class Main {
    public static void main(String[] args) {

        List<customPoint> pointList2 = new ArrayList<>();
        pointList2.add(new customPoint(10, 10));
        pointList2.add(new customPoint(1, 8));
        pointList2.add(new customPoint(5, 2));
        pointList2.add(new customPoint(1, 2));
        pointList2.add(new customPoint(5, 5));
        pointList2.add(new customPoint(10, 1));

        System.out.println("current list");
        for (customPoint temp : pointList2) {
            System.out.println("x: " + temp.getX() + "  " + "y: " + temp.getY());
        }

        System.out.println("sorted list");

        Collections.sort(pointList2);

        for (customPoint temp : pointList2) {
            System.out.println("x: " + temp.getX() + "  " + "y: " + temp.getY());
        }

    }

}

결과

current list
x: 10  y: 10
x: 1  y: 8
x: 5  y: 2
x: 1  y: 2
x: 5  y: 5
x: 10  y: 1
sorted list
x: 10  y: 1
x: 1  y: 2
x: 5  y: 2
x: 5  y: 5
x: 1  y: 8
x: 10  y: 10
반응형