Question

I have created my own class of which I want to create my TreeSet. My class looks like this :

class mytree implements Comparable
{
    int line_no;
    line_segment line[];

    public int compareTo(Object obj)
    {
        tree t = (tree)obj;
        if(this.line_no == t.line_no)
            return 0;
        if(this.line[line_no]>t.line[line_no])
            return 1;
        else
            return -1;

    }
}

I am defining new objects of the class and then inserting them into the TreeSet. In cases I am finding out values like

mytree up = tree.lower(n1);
mytree down = tree.higher(n2);

but if I try to check whether the values of up and down exist in the tree then it sometimes happen that the tree says that the values don't exists in the tree and sometimes it says the values do exist. Though I have handled the case of 0 in compare method what could be the possible error in my creating of the tree.

Was it helpful?

Solution

There are many things wrong in this code. First of all, you're not respecting the Java conventions at all. Second, you're not using generics, as if we were still in 2004, when Java 5 didn't exist yet. Third, your class doesn't represent a tree, so it shouldn't be named mytree. Fourth, your compareTo() method is wrong. It's supposed to be symmetric:

A > B <==> B < A

If A and B's line[line_no] are equal, then if you compare them with A.compareTo(B), the comparison method will return -1. And if you compare them with B.compareTo(A), it will return -1 as well. So you have A < B and B < A at the same time.

OTHER TIPS

    if(this.line_no == t.line_no)
        return 0;
    if(this.line[line_no]>t.line[line_no])
        return 1;

You're comparing two different things in these two checks. I'd expect you should be comparing the same thing, e.g.

    if(this.line_no == t.line_no)
        return 0;
    if(this.line_no > t.line_no)
        return 1;

or

    // also note you probably mean t.line[t.line_no] instead of t.line[line_no]
    if(this.line[line_no] == t.line[t.line_no])
        return 0;
    if(this.line[line_no]>t.line[t.line_no])
        return 1;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top