Не могу разобраться, почему не удается создать очередь с приоритетом на вес(weight
) объекта: элементы должны доставаться в неубывающем виде, однако такого не происходит.
Необходимо было создать класс вершины - Vertex
со своим весовым значением (weight
):
public class Vertex implements Comparable<Vertex>{
public char label;
public int weight; // Вес для вершины
public boolean isVisited;
public List<Vertex> adjList; // Список смежности
public Vertex p; // Родительская вершина
public Vertex(char label) {
this.label = label;
isVisited = false;
adjList = new ArrayList<>();
}
@Override
public String toString() {
return String.valueOf(label);
}
@Override
public int compareTo(Vertex o) {
if(this.weight == o.weight)
return this.label - o.label;
return this.weight - o.weight;
}
}
Реализован интерфейс Comparable, чтобы очередь была в неубывающем виде Далее создал класс, чтобы проверить работоспособность очереди:
public class PriorityTest {
public static void main(String[] args) {
PriorityQueue<Vertex> priorityQueue = new PriorityQueue<>();
Vertex v1 = new Vertex('1'); // 0
Vertex v2 = new Vertex('2'); // 1
Vertex v3 = new Vertex('3'); // 2
Vertex v4 = new Vertex('4'); // 3
Vertex v5 = new Vertex('5'); // 4
Vertex v6 = new Vertex('6'); // 5
v1.weight = 0;
v2.weight = Integer.MAX_VALUE;
v3.weight = Integer.MAX_VALUE;
v4.weight = Integer.MAX_VALUE;
v5.weight = Integer.MAX_VALUE;
v6.weight = Integer.MAX_VALUE;
priorityQueue.offer(v1);
priorityQueue.offer(v2);
priorityQueue.offer(v3);
priorityQueue.offer(v4);
priorityQueue.offer(v5);
priorityQueue.offer(v6);
v2.weight = 6;
v3.weight = 1;
v4.weight = 5;
System.out.println("queue");
while(priorityQueue.peek() != null) {
Vertex v = priorityQueue.poll();
System.out.println(v.label + " - " + v.weight);
}
}
}
Ожидал увидеть :
queue
1 - 0
3 - 1
4 - 5
2 - 6
5 - 2147483647
6 - 2147483647
Однако выводится:
queue
3 - 1
2 - 6
4 - 5
5 - 2147483647
6 - 2147483647
Не могу понять, в чем ошибка