티스토리 뷰

Java

[Java] - Comparable 과 Comparator

영지는 달리는중 2020. 11. 24. 15:59

자바 객체 정렬 방법 

Comparable 인터페이스 

  • 객체 자신이 가지고 있는 자신의 정렬 기준을 정의하는 인터페이스
  • 직접 클래스를 만들때 해당 클래스 객체의 정렬 기준을 미리 설정해두기 위해 구현하는 인터페이스
  • 래퍼 클래스나 String과 같이 자바에서 정렬이 가능한 타입들은 모두 Coparable을 구현하고 있다

Int ComporeTo()메소드 리턴값

  • 음수일 경우 : 두 요소의 위치를 바꿈 
  • 양수일 경우: 두 요소의 위치를 그대로 

만약 배열이 {3,6,1}이라면 처음 비교할 때 compareTo의 파라미터값은 3, this 값은 6

package Programmers.sort;

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

public class ComparablePractice {

    static class Song implements Comparable<Song> {

        private int id;
        private String name;

        public Song(int id, String name) {
            this.id = id;
            this.name = name;
        }

        public int getId() {
            return id;
        }

        @Override
        public int compareTo(Song o) {
            if (o.getId() < this.getId()) {
                return -1;
            }
            return 0;
        }
    }

    public static void main(String args[]) {
        Song song = new Song(5, "hi");
        Song song2 = new Song(3, "hello");
        Song song3 = new Song(1, "haha");
        Song song4 = new Song(7, "hoho");

        List<Song> songs = new ArrayList<>();
        songs.add(song);
        songs.add(song2);
        songs.add(song3);
        songs.add(song4);

        //내림차순 정렬
        Collections.sort(songs);

        for (Song i : songs
        ) {
            System.out.println(i.getId());
        }
    }
}

 

Complarator 인터페이스

  • 정렬 기준만 가진 객체를 구현하는 인터페이스
  • sort() 메소드에 이 정렬 기준을 부여해주면 Comparable로 구현된 디폴트 기준을 무시하고 Comparator의 정렬 기준으로 정렬된다
  • 코드 수정이 불가한 기본 객체들을 디폴트와 다른 기준으로 정렬하기 위해 사용

Int Compare(o1,o2)메소드 리턴값

  • 음수일 경우 : 두 요소의 위치를 바꿈 
  • 양수일 경우: 두 요소의 위치를 그대로 

만약 배열이 {3,6,1}이라면 처음 비교할 compate o1 6, o2 3

package Programmers.sort;

import java.util.*;

public class ComparatorPractice {

    static class Song {

        private int id;
        private String name;

        public Song(int id, String name) {
            this.id = id;
            this.name = name;
        }

        public int getId() {
            return id;
        }

    }

    public static void main(String args[]) {
        Song song = new Song(5, "hi");
        Song song2 = new Song(3, "hello");
        Song song3 = new Song(1, "haha");
        Song song4 = new Song(7, "hoho");

        List<Song> songs = new ArrayList<>();
        songs.add(song);
        songs.add(song2);
        songs.add(song3);
        songs.add(song4);

        //오름차순정렬
        Collections.sort(songs, (o1, o2) -> {
            if (o2.getId() > o1.getId()) {
                return -1;
            }
            return 0;
        });

        songs.stream().forEach(i -> {
            System.out.println(i.getId());
        });

    }
}
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함