简体   繁体   中英

Comparator initialisation inside constructor of another class

I came across the following code. Here, how are we initializing a comparator in the constructor of priority queue?

I know comparator is an interface in Java and should be implemented in another class.

Ideally, we should implement comparator in a class and use its initialization in the PriorityQueue constructor.

But the following code works. How?

  PriorityQueue<ArrayList<Integer>> heap = new PriorityQueue<ArrayList<Integer>>(10, new Comparator<ArrayList<Integer>>(){
            public int compare(ArrayList<Integer> list1, ArrayList<Integer> list2) {
                return list1.get(2) - list2.get(2);
            }

well in reference code snap, priority queue object has been created using constructor which takes two object as arguments viz type int and of type Comparator.

In reference code snap, Comparator type object has been created as anonymous inner class and passed to PriorityQueue constructor as second object.

for better understanding you can break that statement in below two statement. 1st will create comparator object, 2nd will pass that object to blocking queue.

Comparator> comparator = new Comparator>(){ public int compare(ArrayList list1, ArrayList list2) { return list1.get(2) - list2.get(2); } };

PriorityQueue> heap = new PriorityQueue>(10, comparator );

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