Override methods hashCode()
and equals(Object obj)
to avoid duplicate and use method contains
to check if the object exists or not.
class Element {
int i, j, distance;
public Element(int i, int j, int distance) {
super();
this.i = i;
this.j = j;
this.distance = distance;
}
@Override
public int hashCode() {
return Objects.hash(i, j);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Element element = (Element) obj;
return Objects.equals(i, element.i) && Objects.equals(j, element.j) ;
}
@Override
public String toString() {
return "Element [i=" + i + ", j=" + j + ", distance=" + distance + "]";
}
}
Check like below
PriorityQueue<Element> pq = new PriorityQueue<>((a, b) -> (a.distance == b.distance ? a.i == b.i ? a.j - b.j : a.i - b.i : a.distance - b.distance));
pq.add(new Element(i1, j1, d1)); // element values
Element e2 = new Element(i2, j2, d2);
if(!pq.contains(e2)) {
pq.add(e2);
}