我有一个优先级队列,其中包含一对点 我一直在迭代该队列,并将一对中的每个点插入树集中。
问题是我想维护优先级队列中的顺序 我该如何实现树集的比较器?
答案 0 :(得分:1)
这是一种可能性。我没有将点本身插入TreeSet
,而是一个包装器,用于跟踪它们在PriorityQueue
中的顺序。这样做的好处是我们不需要修改Point
类本身。
这是包装类:
import java.util.PriorityQueue;
import java.util.TreeSet;
public class Sortable<T> implements Comparable<Sortable<T>> {
T element;
int order;
public Sortable(T element, int order) {
this.element = element;
this.order = order;
}
@Override
public int compareTo(Sortable<T> o) {
return order - o.order;
}
}
现在你可以做到:
public void transfer(PriorityQueue<PointPair> from, TreeSet<Sortable<Point>> to) {
PointPair pp = from.poll();
int count = 0;
while (pp != null) {
to.add(new Sortable<Point>(pp.getLeftPoint(), count));
count++;
to.add(new Sortable<Point>(pp.getRightPoint(), count));
count++;
pp = from.poll();
}
}