Java

객체를 원하는 조건에 따라 정렬

yougeun 2022. 11. 13. 16:36
728x90

객체를 원하는 조건에 따라 정렬

public static void main(String[] args) {
    int[][] arr = {{1,1},{-1,1},{2,3},{4,3},{0,0},{1,2}};
    Coordinate[] coordinates = new Coordinate[arr.length];
    for(int i=0; i<arr.length;i++){
        coordinates[i] = new Coordinate(arr[i][0],arr[i][1]);
    }
    System.out.println(Arrays.toString(coordinates));
    Arrays.sort(coordinates,Coordinate::compareTo);
    System.out.println(Arrays.toString(coordinates));
}

static class Coordinate implements Comparable<Coordinate> {
    int x;

    int y;

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


    @Override
    public int compareTo(Coordinate o) {
        return (Math.abs(x)<<1+Math.abs(y)<<1)-(Math.abs(o.x)<<1+Math.abs(o.y)<<1);
    }

    @Override
    public String toString() {
        return "x:"+x+" y:"+y;
    }
}

출력 결과

좌표 (x, y) 값을 알고 있을 때 원점에서 (x, y)까지의 거리가 짧은 순으로 정렬하는 코드이다. 객체 class안에 Comparable <객체 Type>을 implements 하여 compareTo를 구현한 후 Arrays.sort를 이용하면 원하는 조건에 따라 쉽게 정렬 가능하다.

728x90