Jass_Manak's blog

By Jass_Manak, history, 3 years ago, In English

I came across a question where I have to store to pair in PriorityQueue in Java. But Java does not have anything like make_pair in C++. What can be the alternate used in Java for making a pair?

 
 
 
 
  • Vote: I like it
  • +1
  • Vote: I do not like it

»
3 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by Jass_Manak (previous revision, new revision, compare).

»
3 years ago, # |
  Vote: I like it +15 Vote: I do not like it

The simplest way would probably be making your own pair class and defining a custom comparator.

»
3 years ago, # |
  Vote: I like it +13 Vote: I do not like it

Still not available in Java standard library. So all you need is to switch to Scala :)

  import java.util.PriorityQueue
  
  val pq = new PriorityQueue[(Int, String)]
  pq.add((1, "one"))
  pq.add((2, "two"))
»
3 years ago, # |
  Vote: I like it +8 Vote: I do not like it

You need to create a java class for pair an implementation is given below :

class pair implements Comparable{ int a,b;

public pair(int a, int b) {
        this.a = a;
        this.b = b;
    }
    public int compareTo(pair o) {
        if(this.a==o.a)
            return this.b - o.b;
        return this.a - o.a;
    }
}

pair class implements comparable interface because priority queue will use this interface compareTo method to compare elements.

you can define priority queue as follows

PriorityQueue<pair> pq = new PriorityQueue<>();
    pq.add(new pair(1,2));
»
3 years ago, # |
  Vote: I like it +8 Vote: I do not like it

Abit weird method but if the numbers in your pair are small enough, you insert then into your priority queue by inserting a*(constant)+b.

»
3 years ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

//import Point class or define a your own custom class Point import java.awt.Point; //define your priorityQueue with type 'Point' and comparator PriorityQueue<Point> pq = new PriorityQueue<>( new Comparator<Point>(){ public int compare( Point a , Point b ) { // define your comparison return Integer.compare( a.x ,b.x ); } }); //insert into priorityQueue pq.offer( new Point( 5,6 ) );