DanielX2010
DanielX2010

Reputation: 1908

PriorityQueue with external parameters

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!

Upvotes: 2

Views: 760

Answers (2)

Tony Rad
Tony Rad

Reputation: 2509

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));

Upvotes: 4

amit
amit

Reputation: 178421

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.

Upvotes: 4

Related Questions