I was testing the functionality of Min-PriorityQueue in Java. This is how I implemented it. But at runtime, .contains() return false for an object, I believe is present in the data-structure. Any insights where this is going wrong ?
public class NodeStruct implements Comparable<NodeStruct>{
public String FName;
public String LName;
public int age;
public NodeStruct(String fname, String lName, int age){
this.FName = fname;
this.LName = lName;
this.age = age;
}
@Override
public int compareTo(NodeStruct that) {
return (this.age - that.age);
}
public boolean equals(NodeStruct obj){
return (obj.age == this.age && obj.FName.equals(this.FName) && obj.LName.equals(this.LName));
}
public void print(){
System.out.println("FName, LName, age : " + this.FName + "," + this.LName + "," + this.age);
}
}
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Main
{
public static void main (String[] args) throws java.lang.Exception
{
PriorityQueue<NodeStruct> PQ = new PriorityQueue<NodeStruct>(5);
NodeStruct tmp = new NodeStruct("Harry", "Potter", 15);
PQ.offer(tmp);
tmp = new NodeStruct("Ron", "Weasley", 14);
PQ.offer(tmp);
tmp = new NodeStruct("Hermione", "Granger", 16);
PQ.offer(tmp);
boolean isPresent = PQ.contains(new NodeStruct("Ron", "Weasley", 14));
System.out.println("Is Present : " + isPresent);
NodeStruct tmp2 = PQ.peek();
tmp2.print();
}
}
The output shows :
Is Present : false
FName, LName, age : Ron,Weasley,14