2

I have a project where I have a class Halfedge (olny .class file, so no way to modify it). I want to create a PriorityQueue. In order to determine which element is bigger, I need not only the fields inside the Halfedge class, but also a HashMap that I create in my code.

The thing is: when I define the Comparator class specific for the Halfedge, I cannot include any parameters.

My question is: how can I implement a comparator class for my Halfedge class using outside parameters? (or simply, how shoul I construct that PriorityQueue)

Thanks a lot!

1
  • Not sure I am following. Can't you include a reference to the HashMap object in the constructor (and later as a member) of the Comparator? Or as an alternative - if the Comparator is an anonymous inner class - you can access final variables from the method it was created. Commented Nov 12, 2012 at 23:08

2 Answers 2

4

Please take a look at the following code:

public class HalfedgeComparator
        implements Comparator<Halfedge>;
{

  Object param1 = null;

  public HalfedgeComparator (Object param1) {
    this.param1= param1;
  }

  public int compare(Halfedge item1, Halfedge item2)
  {
    return ...;
     //your logic here where you can use the param1 passed in the constructor
  }
}

and the client code may be:

Collections.sort(yourListHere, new HalfedgeComparator(yourExternalParamHere));
Sign up to request clarification or add additional context in comments.

Comments

4

Note that you can access a final variable from an anonymous inner class, and you can use this for your need.

Here is a simple example:

public static void main(String args[]) {
    final Map<String,Integer> map = new HashMap<>();
    String s1 = "a";
    String s2 = "b";
    String s3 = "c";
    map.put(s2, 1);
    map.put(s1, 2);
    map.put(s3, 3);
    PriorityQueue<String> pq = new PriorityQueue<>(3, new Comparator<String>() {

        @Override
        public int compare(String o1, String o2) {
            return map.get(o1).compareTo(map.get(o2));
        }
    });
    pq.add(s1);
    pq.add(s2);
    pq.add(s3);
    while (pq.isEmpty() == false) 
        System.out.println(pq.poll());
}

Note that the Comparator object is using the map local variable. It can be done because the variable map was declared final.


An alternative is passing a reference to the Map in the constructor of the Comparator (if it is not an anonymous inner class), store it as a field and use it later on.


In any case - you must make sure the data in the Map for some element does not change after the element was inserted to the PriorityQueue - if it happens - your data structure will become corrupted and you will get an undefined behavior.

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.