PriorityQueue has objects with the same priority

后端 未结 2 874
渐次进展
渐次进展 2020-12-16 00:59

I\'m using a priority queue to sort and use a large number of custom objects. The objects have a \"weight\" that is their natural ordering. However, different objects that a

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-16 01:52

    You could use an automatically-incremented sequence number as a secondary key, and use it to break ties.

    Javadoc for PriorityBlockingQueue includes an example of this technique:

    Operations on this class make no guarantees about the ordering of elements with equal priority. If you need to enforce an ordering, you can define custom classes or comparators that use a secondary key to break ties in primary priority values. For example, here is a class that applies first-in-first-out tie-breaking to comparable elements. To use it, you would insert a new FIFOEntry(anEntry) instead of a plain entry object.

    class FIFOEntry>
         implements Comparable> {
       final static AtomicLong seq = new AtomicLong();
       final long seqNum;
       final E entry;
       public FIFOEntry(E entry) {
         seqNum = seq.getAndIncrement();
         this.entry = entry;
       }
       public E getEntry() { return entry; }
       public int compareTo(FIFOEntry other) {
         int res = entry.compareTo(other.entry);
         if (res == 0 && other.entry != this.entry)
           res = (seqNum < other.seqNum ? -1 : 1);
         return res;
       }
     }
    

提交回复
热议问题