3
votes

I am in the process of upgrading our project to java 7. I ran into the Illegal Argument exception for Collections.sort(). I know the cause of the exception is the new Timsort in java 7 (I did go throw though all the questions raised previously on this issue). Now I need to modify the compare logic to overcome the exception. Here is my compare method

if (o1.isLookup() && !o2.isLookup()) {
    return -1;
}
if (!o1.isLookup() && o2.isLookup()) {
    return 1;
}

if (o1.dependsOn(o2)) {
    return 1;
}
if (o2.dependsOn(o1)) {
    return -1;
}
return 0;
  1. I tried overriding the equals() method , with the same logic as compare, thinking if equals and compare return the same result it should resolve the issue; but it didn't work as expected .

  2. When I split the compare method into two with separate comparators as shown below then the sort(using both comparators) does not throw any exception. What could be the possible reason?

Code Below:

protected Comparator<EntityWrapper> getComparator2() {      
    return new Comparator<EntityWrapper>() {
        public int compare(EntityWrapper o1, EntityWrapper o2) {
            if (o1.dependsOn(o2.entityClass)) {
                // This depends on otherWrapper
                return 1;
            }
            if (o2.dependsOn(o1.entityClass)) {
                // OtherWrapper depends on this
                return -1;
            }
            return 0;
        }
    };
}

protected Comparator<EntityWrapper> getComparator1() {
    return new Comparator<EntityWrapper>() {
public int compare(EntityWrapper o1, EntityWrapper o2) {
        if (o1.isLookup() && !o2.isLookup()) {
            return -1;
        }
        if (!o1.isLookup() && o2.isLookup()) {
            return 1;
        }
        return 0;
    };
}
1
is it possible that o1.dependsOn(o2) and o2.dependsOn(o1) are both true? - Henry
It is hard to comment unless we see what dependsOn and isLookup method do here. - Rohit Jain
Can't speak for your specific example, but make sure your comparison function respects the concept of Strict Weak Ordering. That is, if a < b, then b should be > a and stuff like that. - Cubicle Dragon
@Henry probably nailed it for your specific case. If o1 and o2 both depend on each other, your comparator will return that o1 is greater than o2 if called with (o1, o2) but will return that o2 is greater if called with (o2, o1), which totally confuses the sorting algorithm. - Cubicle Dragon
Post SSCCE that clearly shows the problem. - PM 77-1

1 Answers

0
votes

Aren't you missing ".entityClass" such as:

if (o1.isLookup() && !o2.isLookup()) {
    return -1;
}
if (!o1.isLookup() && o2.isLookup()) {
    return 1;
}

if (o1.dependsOn(o2.entityClass)) {
    return 1;
}
if (o2.dependsOn(o1.entityClass)) {
    return -1;
}
return 0;