0

I have a priority queue that being manipulated in a while(true) loop inside a thread. In some cased I want to take the queue content and sort it in an array. I do it this way:

Object[] array = sellQueues[0].toArray();
Arrays.sort(array);

The compare method for this priority queue is as follow:

public int compare(Order o1, Order o2) {
            try {
                if (o1.getBroker().getOrdersPriority() > o2.getBroker().getOrdersPriority())
                    return 1;
                else if (o1.getBroker().getOrdersPriority() < o2.getBroker().getOrdersPriority())
                    return -1;
                else {
                    if (o1.getBeginDate().before(o2.getBeginDate()))
                        return 1;
                    else if (o1.getBeginDate().after(o2.getBeginDate()))
                        return -1;
                    else {
                        if (o1.getBeginTime().before(o2.getBeginTime()))
                            return 1;
                        else if (o1.getBeginTime().before(o2.getBeginTime()))
                            return -1;
                        else
                            return 0;
                    }
                }
            } catch (NullPointerException e) {
                return 0;
            }
        }

For some reason, Sometimes I get the error:

java.lang.IllegalArgumentException: Comparison method violates its general contract!

kitsuneFox
  • 1,243
  • 3
  • 18
  • 31
  • 1
    ***For some reason, Sometimes I get the error....*** how can we help with such an descriptive information??? – ΦXocę 웃 Пepeúpa ツ May 08 '17 at 07:08
  • Are my eyes going, or is the else that compares the `o1.getBeginTime()` doing the same `.before` in both the `if` and `else if` (i.e., shouldn't one of those be a `.after()`)? – KevinO May 08 '17 at 07:24

1 Answers1

1

The implementation in the comparator violates its general contract because: Suppose Order A,B,C has the same broker, A has null begin date, B has begin date 1/1/2017 and C has begin date 01/01/2018. Then

  1. A equals B and A equals C by the comparator.
  2. B is larger than C by the comparator

Hence (2) contradict (1).

To correct the implementation, remove the catch for NullPointerException(bad habit to catch RunTimeException), add methods to compare the properties of Order, and define consistent comparison for null.

samabcde
  • 6,988
  • 2
  • 25
  • 41