푸린세스

TreeSet예제1 11-13 본문

카테고리 없음

TreeSet예제1 11-13

푸곰주 2022. 3. 25. 10:18
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package ex11;
 
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
 
public class Ex11_13 {
 
    public static void main(String[] args) {
        Set set = new TreeSet(); //비교기준을 넣어줘야..
        
        //new TreeSet(new TestComp());
        
        
//        for( int i = 0; set.size() <6 ; i++) {
//            int num = (int)(Math.random()*45)+1;
            set.add(new Test());//형변환에러 , 비교기준이 없어서 에러
            set.add(new Test());//형변환에러 , 비교기준이 없어서 에러
            set.add(new Test());//형변환에러 , 비교기준이 없어서 에러
            set.add(new Test());//형변환에러 , 비교기준이 없어서 에러
            set.add(new Test());//형변환에러 , 비교기준이 없어서 에러
 
//            //set의 add메소드는 비교하면서 저장...
//        }
        
        System.out.println(set);
 
    }
 
}
//둘중에하나 1.저장하는Test객체가 비교기준comparable을 갖고있던가.
//2.Treeset이 비교기준 TestComp를 갖고있던가~~~~
//어디서 제공하던지 간에 비교기준이 꼭필요하다..
 
//comparable을 구현한다면 comparator 안넣어도된다.
//compraable~compareTo(Object o)기본정렬기준구현
//comparator~compare(Object o1, Objectt o2) 다른기준으로 정렬하고자할때
class Test implements Comparable{
 
    @Override
    public int compareTo(Object o) {
        // TODO Auto-generated method stub
        return -1;
    }} //비교기준이 없음.
 
class TestComp implements Comparator{ //비교기준을 하나 생성
 
    @Override
    public int compare(Object o1, Object o2) {
        // TODO Auto-generated method stub
        return 1//0이면 같은객체인걸로;;
    }
    
}
cs

 

add메소드는 비교 후 저장

비교기준이 필요.

 

1.저장하는 객체의 comparable 사용한다. (남이 만든 클래스 객체를 add할때, but우리가 직접 compareTo메소드 수정불가) -기본비교기준

 

2.TreeSet에 비교기준을 제공한다. ( 내가 직접 만들어서 전달한 Comparator)

 

*TreeSet 생성자.

-TreeSet() 기본생성자

-TreeSet(Collection c)

-TreeSet(Comparator comp) <-비교기준제공.