简体   繁体   中英

How to use Comparable to order a prioritylist of objects?

Here is my object class. There are no errors here.

public class AStarNode implements Comparable<AStarNode> {
    AStarNode pathParent;
    int x;
    int y;
    int costFromStart;
    int estimatedCostToGoal;

    public int getCost() {
        return costFromStart + estimatedCostToGoal;
    }

    @Override
    public int compareTo(AStarNode node) {
        int otherValue = node.getCost();
        int thisValue = this.getCost();
        if(thisValue-otherValue > 0) {
            return 1;
        }
        else {
            return 0;
        }
    }
}

Here is something I have within my AStarSearch class. I'm getting errors here and I'm not sure what to do to fix them. I've been trying stuff for the past hour. What I'm trying to do is have a special method for PriorityList which adds the object somewhere into the PriorityList based on one of the objects variables. Can anyone point out where I'm going wrong?

public class PriorityList extends LinkedList {
    public void add(Comparable node) {
        for (int i=0; i<size(); i++) {
            if(node.compareTo(node) == 0) {
                add(i, node);
                return; 
            }
        }
        addLast(node);
    }
}

Your implementation violates the contract of Comparable.

Let's say A's value is 2 and B's value is 1.

If you compare A to B, you'll have 2 - 1 > 0, and you'll thus return 1, meaning that A is bigger than B.

If you compare B to A, you'll have 1 - 2 < 0, and you'll thus return 0, meaning that A is equal to B.

Given this error, any algorithm relying on your comparator will lead to undetermined behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM