티스토리 뷰

package practice;


import java.util.Comparator;

import java.util.TreeSet;


public class ComparatorEx1 {


public static void main(String[] args) {

// TODO Auto-generated method stub


TreeSet set1 = new TreeSet();

TreeSet set2 = new TreeSet(new Descending());

//내림차순으로 트리셋 객체 생성


int[] score = { 30, 50, 10, 20, 40 };


for (int i = 0; i < score.length; i++) {

set1.add(new Integer(score[i]));

set2.add(new Integer(score[i]));

// Integer 타입으로 객체 추가

// set2는 Descending 클래스를 이용하여

// 객체를 생성 했으므로 내림차순 정렬이 되었다.

}

System.out.println("set1 : " + set1);

System.out.println("set2 : " + set2);

}

}


class Descending implements Comparator {

// comparator 인터페이스 구현 부분


public int compare(Object o1, Object o2) {

if (o1 instanceof Comparable && o2 instanceof Comparable) {

// 1번과 2번 객체가 모두 comparable의 인스턴스라면

// 상속을 받은 자식 클래스라면 실행


Comparable c1 = (Comparable) o1;

Comparable c2 = (Comparable) o2;

//comparable 객체 생성


return c1.compareTo(c2) * -1;

//기존 정렬방식의 역으로 변경한다.

}

return -1;

}

}



결과 :
set1 : [10, 20, 30, 40, 50]
set2 : [50, 40, 30, 20, 10]


'java,web study > 3주차 (7월 15일 ~21일)' 카테고리의 다른 글

HashMapEx2 - 점수 계산  (0) 2013.07.19
HashMapEx1 - 로그인  (1) 2013.07.19
TreeSetEx1 - 문자열  (0) 2013.07.19
TreeSetLotto  (0) 2013.07.19
ClickAndDoubleClickEx  (0) 2013.07.19
댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/03   »
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
글 보관함