class명 cannot be cast to class java.lang.Comparable (class명 is in unnamed module of loader 'app'; java.lang.Comparable is in module java.base of loader 'bootstrap')
PriorityQueue에 노드를 넣어서 하고 싶었는데 계속 저 오류가 떴다.
원래 코드는 이랬음.
static class coor1 implements Comparator<coor1>{
int r;
int c;
int s;
public coor1() {
}
public coor1(int r, int c) {
super();
this.r = r;
this.c = c;
}
public coor1(int r, int c, int s) {
super();
this.r = r;
this.c = c;
this.s = s;
}
public int compare(coor1 o1, coor1 o2) {
if (o1.s != o2.s) {
return Integer.compare(o1.s, o2.s);
} else if (o1.r != o2.r) {
return Integer.compare(o1.r, o2.r);
} else {
return Integer.compare(o1.c, o2.c);
}
}
}//coor
public static void main(String[] args) {
PriorityQueue<coor1> pq=new PriorityQueue<>();
pq.add(new coor1(1,1,1));
}
comparator 다중 조건 정렬을 하려고 했는데, 안됐다.
문제는 comparator을 class에 바로 담고서 pq를 생성한 점이었다.
해결한 코드는 아래와 같다.
바로 compare 할 class를 새로 생성해주고, pq를 생성할 때 생성자에 담아주는 것이다.
compare 공부를 안하니까 문제풀때 여기에 막혀서 1시간 넘게 버림...역시 기초공부가 중요하다.
import java.util.Comparator;
import java.util.PriorityQueue;
public class s {
static class coor1 {
int r;
int c;
int s;
public coor1() {
}
public coor1(int r, int c) {
super();
this.r = r;
this.c = c;
}
public coor1(int r, int c, int s) {
super();
this.r = r;
this.c = c;
this.s = s;
}
}
static class CoorComparator implements Comparator<coor1> {
@Override
public int compare(coor1 o1, coor1 o2) {
if (o1.s != o2.s) {
return Integer.compare(o1.s, o2.s);
} else if (o1.r != o2.r) {
return Integer.compare(o1.r, o2.r);
} else {
return Integer.compare(o1.c, o2.c);
}
}
}
public static void main(String[] args) {
PriorityQueue<coor1> pq = new PriorityQueue<>(new CoorComparator());
pq.add(new coor1(1, 1, 1));
}
}