Basic tasks with priority queues in java.

This commit is contained in:
Tomasz Półgrabia 2025-02-10 11:50:56 +01:00
parent 6b89476e26
commit 2edf415e2a
3 changed files with 64 additions and 0 deletions

View file

@ -0,0 +1,38 @@
import java.util.*;
public class Program2 {
public record Element(
int weight) implements Comparable {
public int compareTo(Object o) {
if (!(o instanceof Element)) {
throw new IllegalArgumentException("Got invalid class to compare: " + o.getClass());
}
Element e = (Element)o;
return weight - e.weight;
}
public String toString() {
return "Element{weight = %d}".formatted(weight);
}
}
public static void main(String[] args) {
var pq = new PriorityQueue<Element>();
pq.add(new Element(1));
pq.add(new Element(5));
pq.add(new Element(-3));
pq.add(new Element(-7));
System.out.printf("Hello World: %s\n", pq.remove());
System.out.printf("Hello World: %s\n", pq.remove());
System.out.printf("Hello World: %s\n", pq.remove());
System.out.printf("Hello World: %s\n", pq.remove());
}
}