0

I'm trying to store object to piority queue, each object has its own value. So, I want to get the smallest value when using poll() method. But it doesn't work like I expected.

I add n object with id from 0 to n - 1, then set value for each object.

when I poll the first element, it's always the object with id 0? no matter what value it is. I don't know why ? here is the code:

class Element implements Comparable<Element>{
    int id;
    int value;
    public Element(int id) {
        this.id = id;
    }
    @Override
    public int compareTo(Element e) {
        return Integer.compare(value, e.value);
    }
}


    //main
    Element[] elements = new Element[n];
    Queue<Element> piorityQueue = new PriorityQueue<>();
    for(int i = 0; i < n; ++i){
        elements[i] = new Element(i);
    }
    for(int i = 0; i < n; ++i){
        piorityQueue.add(elements[i]);
    }
    elements[1].value = 4;
    elements[2].value = 3;
    elements[3].value = 2;
    elements[0].value = 5;
    elements[4].value = 1;
    elements[5].value = 0;
    while(!piorityQueue.isEmpty()){
        Element e  = piorityQueue.poll();
        System.out.println(e.id + " " + e.value);
    }

the wrong output here:

0 5
5 0
4 1
3 2
2 3
1 4

please, can someone help me this?

Duc Pham
  • 1
  • 2
  • 2
    You **must not** mutate objects after adding them. Think about it - how would the queue know that you've poked at the innards of things you have already added and it has already sorted - when you added them!? You need to remove then add again if you want to mutate. To discourage you from doing these sorts of things, I would suggest making anything that you rely on in `equals`, `hashCode` or `compareTo` `final` - that way you cannot mutate them. – Boris the Spider Aug 18 '18 at 12:48
  • okay ! now, I understand. Thanks !. – Duc Pham Aug 18 '18 at 12:58

0 Answers0