1

I have created a priority queue using the Java API and I want to remove a specific element from the priority queue at the end of the program. I know it has to do something with the comparator but I can't figure it out. Can someone help? Here's my code:

public static void main(String[] args)
{
    PriorityQueue<Element> X = new PriorityQueue<Element>(100, new ElementComparator());
    X.add(new Element(30, 3));
    X.add(new Element(700, 4.5));
    X.add(new Element(100, 6.2));
    X.add(new Element(2, 8.1));
    System.out.println(X.remove(new Element(100, 6.2)));
}

and here's my Element class:

private int index;
private double value;

public Element(int i, double v) 
{
    index = i;
    value = v;
}

public int getIndex() { return index;};
public double getValue() { return value;};
public void setValue(double v) { value = v;};

And here's the comparator that I created:

public int compare(Element o1, Element o2)
{
    int idx1 = o1.getIndex();
    int idx2 = o2.getIndex();
    if (idx1 < idx2) {
        return -1;
    } else if (idx1 > idx2) {
        return 1;
    } else {
        return 0;
    }
}

public boolean equals(Element o1, Element o2) 
{
    return o1.getIndex() == o2.getIndex();
}

I appreciate your help...

3
  • System.out.println(X.remove(new Element(100, 6.2))); will print if the element was actually removed from X, is that what you are trying to achieve? or are you trying to print X? Commented Feb 6, 2012 at 0:42
  • The compareTo function is for sorting. The equality method is needed for remove. See @johncarl's answer below for the correct signature of this method. Commented Feb 6, 2012 at 0:42
  • Also: It is a good practice and a java convention to name non-constant variables with a name starting with lower case letter. Commented Feb 6, 2012 at 0:43

1 Answer 1

1

You need to define equals() and hashcode() on your Element object as such:

public class Element{
    private int index;
    private double value;

    public Element(int i, double v)
    {
        index = i;
        value = v;
    }

    public int getIndex() { return index;}
    public double getValue() { return value;}
    public void setValue(double v) { value = v;}

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Element)) return false;

        Element element = (Element) o;

        if (index != element.index) return false;

        return true;
    }

    @Override
    public int hashCode() {
        return index;
    }
}

Defining equals() on the ElementComparator does not perform the same task.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.