import java.util.TreeSet;컴파일 및 실행은 다음 결과를 반환합니다.
class 포인트 {
int x,y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
}
public class ImpComparableWrong {
public static void main(String[] args) {
TreeSetd = new TreeSet ();
d.add(새 Point(2,4));
d.add(새 Point(1,7));
d.add(새 Point(5,3));
System.out.println(d.size());
}
}
스레드 "main"의 예외 java.lang.ClassCastException : TreeSet.Point를 java.lang.Comparable그 이유는 Point 클래스가 Comparable을 사용하여 TreeSet이 Point 객체를 보유할 수 있도록 합니다. 추가된 객체는 TreeSet의 요소, add()은 예외를 발생시킵니다ClassCastException입니다. 객체를 비교할 수 있게 만들려면 Comparable.
/> java.util.TreeMap.put(알 수 없는 소스)
java.util.TreeSet.add(알 수 없는 소스)
TreeSet.Comparable.main(Comparable.java:17)
import java.util.Iterator;이 프로그램은 다음 결과를 출력합니다.
import java.util.TreeSet;
class Point는 Comparable{
int x,y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
public int compareTo(Point p) {
double dp2 = (double) Math.sqrt(Math.pow(p.x,2) + Math.pow(p.y,2));
double dp = (double) Math.sqrt(Math.pow(x,2) + Math.pow(y,2));
if(dp > dp2)
1을 반환합니다.
else
0을 반환합니다.
}
}
public class Comparabletest {
public static void main(String[] args) {
TreeSettset = new TreeSet ();
tset.add(새 Point(2,4));
tset.add(새 포인트(1,7));
점 a = 새 점(2,5);
반복자<점> 반복자 = tset.iterator();
while(iterator.hasNext()){
포인트 p = iterator.next();
System.out.print(px +", "+ p.y);
System.out.println(" | p > a: "+p.compareTo(a));
}
}
}
2, 4 | p > 답: 0
1, 7 | p > a : 1
< / pre>References :
Javadoc : TreeSet 클래스 < / a>
Please disable your ad blocker and refresh the window to use this website.