상세 컨텐츠

본문 제목

[JAVA] Comparable과 Comparator

Spring/JAVA

by Chan.94 2022. 7. 19. 12:36

본문

반응형

Comparable 

Wrapper 객체는 모두 Comparable 인터페이스를 구현하고 있다.(Integer, Double, String..)

 

Comparable에는 compareTo() 메소드가 존재하고 적절하게 오버라이딩하여 정렬을 할 수 있게 한다.

public class ComparableTest {

	public static void main(String[] args) {
        //TreeSet은 오름차순으로 데이터를 저장
        TreeSet<Integer> treeSet = new TreeSet<Integer>();

        treeSet.add(30000000);
        treeSet.add(20000000);
        treeSet.add(10000000);

        Iterator<Integer> iterator = treeSet.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
		
        TreeSet<Product> treeSet1 = new TreeSet<Product>();

        treeSet1.add(new Product("냉장고", 10000000)); // 금액 작은 순으로 저장
        treeSet1.add(new Product("컴퓨터", 20000000));
        treeSet1.add(new Product("에어컨", 30000000));

        Iterator<Product> iterator1 = treeSet1.iterator();
        while(iterator1.hasNext()){
        	Product product = iterator1.next();
            System.out.println(product.getName() + "  :  " + product.getAmt());
        }
    }

}
class Product implements Comparable<Product> {

    private String name;
    private int amt;

    public Product(String name, int amt){
        this.name = name;
        this.amt = amt;
    }
    
    /**
     * 내림차순 정렬
     */
    @Override
    public int compareTo(Product o) {
        if(amt < o.getAmt()) return 1;
        else if(amt == o.getAmt()) return 0;
        else return -1;
    }

    public String getName() {
        return name;
    }

    public int getAmt() {
        return amt;
    }
}
10000000
20000000
30000000
에어컨  :  30000000
컴퓨터  :  20000000
냉장고  :  10000000

TreeSet은 오름차순으로 데이터를 저장한다는 특징을 가지고 있다. compareTo()를 오버라이딩하여 내림차순으로 정렬되도록 변경하였다.

 

Comparator

Comparable 인터페이스가 구현되지 않은 클래스를 정렬시키려면 Comparator 인터페이스를 구현한 클래스로 정렬시킬 수 있다. 

Comparator 객체를 이용하면 Comparable 미구현 클래스도 정렬을 시킬 수 있다는 뜻이다.

public class ComparatorTest {

	public static void main(String[] args) {
		
        //내림차순
        TreeSet<Person> treeSet = new TreeSet<Person>(new DescendingComparator());

        treeSet.add(new Person("손흥민", 2));
        treeSet.add(new Person("박지성", 1));
        treeSet.add(new Person("차범근", 3));

        Iterator<Person> iterator = treeSet.iterator();
        while(iterator.hasNext()){
        Person person = iterator.next();
            System.out.println(person.getName() + "  :  " + person.getRank());
        }
        System.out.println();
        //오름차순
        TreeSet<Person> treeSet1 = new TreeSet<Person>(new AscendingComparator());

        treeSet1.add(new Person("손흥민", 2));
        treeSet1.add(new Person("박지성", 1));
        treeSet1.add(new Person("차범근", 3));

        Iterator<Person> iterator1 = treeSet1.iterator();
        while(iterator1.hasNext()){
            Person person = iterator1.next();
            System.out.println(person.getName() + "  :  " + person.getRank());
        }
    }

}
class Person {

    private String name;
    private int rank;

    public Person(String name, int rank){
        this.name = name;
        this.rank = rank;
    }

    public String getName() {
        return name;
    }

    public int getRank() {
        return rank;
    }
}

class AscendingComparator implements Comparator<Person> {
    @Override
    public int compare(Person o1, Person o2) {
        if(o1.getRank() < o2.getRank()) return -1;
        else if(o1.getRank() == o2.getRank()) return 0;
        else return 1;
    }
}

class DescendingComparator implements Comparator<Person> {
    @Override
    public int compare(Person o1, Person o2) {
        if(o1.getRank() < o2.getRank()) return 1;
        else if(o1.getRank() == o2.getRank()) return 0;
        else return -1;
    }
}
차범근  :  3
손흥민  :  2
박지성  :  1

박지성  :  1
손흥민  :  2
차범근  :  3
반응형

관련글 더보기

댓글 영역

>