Home > Enterprise >  different sort outcome(SortedSet) in debug mode vs normal run
different sort outcome(SortedSet) in debug mode vs normal run

Time:12-21

so i wrote a comparator to sort out objects of the type Polynom (polynomials but in my lang basically). when i iterate slowly over it with a debugger i seem to get the result im expecting. yet when i run it, one of them craps out and returns the wrong value in the comparison which should be very straight forward.

the Polynom object is as follows:

public class Polynom<E> implements IPolynom<E> , Comparable<Polynom<E>>{
    private SortedMap<Integer, FieldMember<E>> coefficients = new TreeMap<>();

while IPolynom is just an interface to define the methods E can be either a complex number (which i also wrote and includes its methods and two fields real and image but its irrelevant to the error)

    public int compareTo(Polynom<E> o) {
    Polynom<E> p1 = new Polynom<>(this);
    Polynom<E> p2 = new Polynom<>(o);
    int deg,co;
    while(!p1.coefficients.isEmpty() && !p2.coefficients.isEmpty())
    {
    deg = p1.degree() - p2.degree();
    if(deg != 0)
        return deg;
    co = p1.getCoefficient(p1.degree()).compareTo(p2.getCoefficient(p2.degree()));
    if(co != 0)
        return co;
    p1.coefficients.remove(p1.degree());
    p2.coefficients.remove(p2.degree());
    
    }
    return (p1.degree() - p2.degree());
}

this is the compareTo method that i wrote and the method degree() simply returns the degree of x in this scenario the coefficient part is never reached in this example so ill skip over it the objects being compared are as follows:

p1 = Polynom: (1.00 0.00i)x^5

p2 = Polynom: (-1.00-5.00i)x^7

the comparison should be straight forward and indicate that p2 is greater than p1 however when i run the opposite is returned when i debug (and specifically iterate over the lines as they happen) the method returns the correct result. if i skip over it even in debug it still returns the wrong result in my main method im adding a bunch of Polynom type objects to a SortedSet and the ordering turns out to be wrong only on a single object (the one being p1 in this case which should be the "smallest" of them and go first up in the sorted set) im really at loss here...

please tell me if theres any other details that i need to add that would make the situation clearer as this is a fairly large project

p.s. all of this is done in eclipse (without any extensions)

CodePudding user response:

my mistake was making .toString() change the state of the object so the debugger didnt tell the whole story! thanks alot guys

  • Related