meong_j
기록하는 습관.
meong_j
전체 방문자
오늘
어제
  • 분류 전체보기 (176)
    • 개인 공부 정리 (0)
    • 서버 운영 (37)
      • Linux (36)
    • Frontend (11)
      • Vue.js (10)
    • Backend (70)
      • Java (4)
      • Python (22)
      • Django (38)
      • Spring (6)
    • Database (5)
      • Oracle (4)
      • MySQL (1)
      • MariaDB (0)
    • Android (14)
      • Kotlin (6)
    • 배포 (9)
      • Docker (8)
      • AWS (1)
    • IT_study (29)
      • Coding test (17)
      • 알고리즘 (5)
      • 스터디 (6)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • github

인기 글

반응형

태그

  • router-link
  • SASS Variables
  • 중첩라우트
  • 배포인프라
  • docker
  • DHCP
  • django
  • 이차원배열정렬
  • dockersecret
  • gabagecollecter
  • 리눅스방화벽
  • 개발자도서
  • 코틀린자료형
  • dp #알고리즘
  • 테크커리어
  • Kotlin
  • 리눅스인증
  • 안드로이드adaptor
  • Proxy
  • cpu사용률

최근 댓글

최근 글

250x250
hELLO · Designed By 정상우.
meong_j

기록하는 습관.

Backend/Java

[Java] 이차원 배열 정렬하기 CompareTo()

2022. 5. 8. 17:52
728x90
반응형

arr ={ { 2, 7}, {1, 3}, {1, 2}, {2, 5}, {3, 6} } 인 이차원 배열을 { {1, 2}, {1, 3}, {2, 5}, {2, 7}, {3, 6} }로 정렬시키려고 한다.

일차원 배열 같은 경우에는 Arrays.sort(arr); 함수로 자동으로 정렬이 되지만,

이차원 배열은 CompareTo() 함수를 사용하여 크기비교를 해주어야 한다.

class Main {

    public static void main(String[] args) {
        Main t = new Main();
        Scanner kb = new Scanner(System.in);
        int n = kb.nextInt();
        ArrayList<Point> arr = new ArrayList<>();
        for(int i=0; i<n; i++){
            int x = kb.nextInt();
            int y = kb.nextInt();
            arr.add(new Point(x, y));
        }
        Collections.sort(arr);//정렬
        for (Point o : arr) System.out.println(o.x +" "+o.y);
    }
}

배열을 선언 받고, ArrayList 를 오름차순으로 먼저 정렬해준다.

Collections.sort(arr);

 

class Point implements Comparable<Point>{
   
    public int x, y;
    Point(int x, int y){
        this.x = x;
        this.y = y;
    }

    @Override
    public int compareTo(Point o) {
        if(this.x == o.x) return this.y - o.y;//y 오름차순 리턴(음수)
               //내림차순  return o-y - this.y;
        else return this.x - o.x;// x 오름차순 리턴
               //내림차순  return o-x - this.x;
    }
}

(x, y) 좌표를 담는 Point라는 생성자를 생성하고 Comparable<Point> implements 하여 Point 객체를 정렬한다. 

compareTo() 메소드를 오버라이드 하여 오름차순, 내림차순의 경우를 정의 해준다.

x값이 같으면 y값을 빼서 y값을 정렬시키고, 아닌 경우 x값을 정렬시킨다.

 

 

반응형
저작자표시 비영리 변경금지

'Backend > Java' 카테고리의 다른 글

org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.executor.ExecutorException: A query was run and no Result Maps were found for the Mapped Statement It's likely that neither a Result Type nor a Result Map was specified.  (0) 2021.12.22
JDK 8.0 버전 설치 하기  (0) 2021.11.25
eclipse 프로젝트 클린, build 되지 않을 때  (0) 2021.11.19
    'Backend/Java' 카테고리의 다른 글
    • org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.executor.ExecutorException: A query was run and no Result Maps were found for the Mapped Statement It's likely that neither a Result Type nor a Result Map was specified.
    • JDK 8.0 버전 설치 하기
    • eclipse 프로젝트 클린, build 되지 않을 때
    meong_j
    meong_j
    #it #개발일기 #개발공부 #개발자 #백앤드 #생각정리 #시간은 실력에 비례한다 #뭐든지 꾸준히 열심히 #오늘의 내가 내일의 나를 만든다

    티스토리툴바