How can I delete a specific item in the priority queue?

import java.util.*; public class test4 { public static void main(String[] args){ PriorityQueue[] P = new PriorityQueue[10]; P[1] = new PriorityQueue<ClassEntry>(); P[1].add(new ClassEntry(1.2,1)); P[1].add(new ClassEntry(1.5,2)); P[1].add(new ClassEntry(1.2,3)); P[1].add(new ClassEntry(10,4)); P[1].remove(new ClassEntry(10,4));//I can't delete this object??? System.out.println(P[1].size()); ClassEntry ce = (ClassEntry) P[1].peek(); System.out.println(P[1].size()); System.out.println(ce.sim+"\t"+ce.index); } } 

Why can't I delete (10.4)? Can someone teach how to implement ... thanks!

+4
source share
1 answer

ClassEntry must override and implement Object.equals(Object o) to remove to work. For instance:

 class ClassEntry{ float a; int b; public ClassEntry(float a, int b){ //... } @Override public boolean equals(Object o){ if(o instanceof ClassEntry){ ClassEntry c = (ClassEntry)o; return a == ca && b == cb; } return false; } } 

EDIT: As @Jim Garrison noted, if you do not implement equal default values, i.e. compare objects by reference, is used. In this case, for your code to work, you will need to delete it like this:

 PriorityQueue[] P = new PriorityQueue[10]; P[1] = new PriorityQueue<ClassEntry>(); ClassEntry entry = new ClassEntry(10,4); P[1].add(entry); //remove object with the same reference as the added one P[1].remove(entry); 
+4
source

Source: https://habr.com/ru/post/1333535/


All Articles