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?
| № | Пользователь | Рейтинг |
|---|---|---|
| 1 | Benq | 3792 |
| 2 | VivaciousAubergine | 3647 |
| 3 | jiangly | 3631 |
| 4 | Kevin114514 | 3574 |
| 5 | maroonrk | 3521 |
| 6 | strapple | 3515 |
| 7 | Radewoosh | 3461 |
| 8 | tourist | 3428 |
| 9 | turmax | 3378 |
| 10 | Um_nik | 3376 |
| Страны | Города | Организации | Всё → |
| № | Пользователь | Вклад |
|---|---|---|
| 1 | Qingyu | 162 |
| 2 | adamant | 148 |
| 3 | Um_nik | 146 |
| 4 | Dominater069 | 143 |
| 5 | errorgorn | 140 |
| 6 | cry | 138 |
| 7 | Proof_by_QED | 136 |
| 8 | YuukiS | 135 |
| 9 | chromate00 | 134 |
| 10 | soullless | 133 |
| Название |
|---|



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.