TreeSet()
에 저장되는 객체(treeSet.add(?)
)가 Comparable
을 구현하든가, TreeSet(Comparator)
에게 Comparator를 제공해서 정렬기준을 알려줘야 한다.TreeSet
은 저절로 정렬하기 때문에 따로 정렬할 필요가 없다!!String
, Integer
... 일 경우, 기본적으로 Comparable
등의 정렬기준을 구현했기 때문에 내가 따로 정렬기준을 만들 필요가 없는 것?!public class Ex11_13 {
public static void main(String[] args) {
Set set = new TreeSet(); //저절로 정렬하기 때문에 따로 정렬할 필요가 없다!!
// for(int i=0; set.size()<6; i++) {
for(; set.size()<6;) {
int num = (int)(Math.random()*45)+1; //1<=x<46
set.add(new Integer(num));
}
System.out.println(set);
}
}
->
[1, 10, 28, 37, 41, 45]
Integer
는 Comparable
을 구현하고 있다!package ch11;
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
public class Ex11_13_2 {
public static void main(String[] args) {
Set set = new TreeSet();
for(; set.size()<6;) {
int num = (int)(Math.random()*45)+1; //1<=x<46
set.add(new Test());
}
System.out.println(set);
}
}
class Test implements Comparable{
// 비교기준
@Override
public int compareTo(Object o) {
return -1;
}
}
->
[ch11.Test@3b22cdd0, ch11.Test@1e81f4dc, ch11.Test@4d591d15, ch11.Test@65ae6ba4, ch11.Test@48cf768c, ch11.Test@59f95c5d]
Test
는 Comparable
을 구현하고 있다!package ch11;
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
public class Ex11_13_2 {
public static void main(String[] args) {
Set set = new TreeSet(new TestComp()); //저절로 정렬하기 때문에 따로 정렬할 필요가 없다!!
// for(int i=0; set.size()<6; i++) {
for(; set.size()<6;) {
int num = (int)(Math.random()*45)+1; //1<=x<46
set.add(new Test());
}
System.out.println(set);
}
}
class Test {
}
class TestComp implements Comparator{
// 비교기준, TreeSet(Comparator)
@Override
public int compare(Object o1, Object o2) {
return 1;
}
}
->
[ch11.Test@1e81f4dc, ch11.Test@4d591d15, ch11.Test@65ae6ba4, ch11.Test@48cf768c, ch11.Test@59f95c5d, ch11.Test@5ccd43c2]
public class AsciiPrint {
public static void main(String[] args) {
char ch = ' ';
// 공백 ' ' 이후의 문자들을 출력한다.
for(int i=0; i<95; i++) {
System.out.print(ch++);
}
}
}
->
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~