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?
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?
| # | User | Rating |
|---|---|---|
| 1 | Benq | 3676 |
| 2 | Kevin114514 | 3657 |
| 3 | jiangly | 3638 |
| 4 | turmax | 3442 |
| 5 | tourist | 3380 |
| 6 | Um_nik | 3353 |
| 7 | strapple | 3350 |
| 8 | squareOf105 | 3346 |
| 9 | heuristica | 3322 |
| 10 | maroonrk | 3310 |
| # | User | Contrib. |
|---|---|---|
| 1 | Qingyu | 158 |
| 2 | nik_exists | 151 |
| 3 | maspy | 150 |
| 4 | AmShZ | 144 |
| 4 | Um_nik | 144 |
| 6 | Errichto | 139 |
| 7 | adamant | 137 |
| 8 | BledDest | 135 |
| 9 | maroonrk | 133 |
| 10 | Proof_by_QED | 131 |
| Name |
|---|



The simplest way would probably be making your own pair class and defining a custom comparator.
Still not available in Java standard library. So all you need is to switch to Scala :)
That’s a weird way to spell C++.
Lol. If that was spelt C++, you would probably see another blog post titled "alternative for BigInteger in C++"
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));Got it!. Thanks.
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.