Issue
I have this program that creates a graph and I implemented it by doing LinkedList<LinkedList> where Edge is
public class Edge<T>{
T src;
T value;
T weight;
public Edge(T src, T value, T weight){
this.src=src;
this.value=value;
this.weight=weight;
}
@Override
public boolean equals(Object obj){
if(obj instanceof Edge){
Edge edge=(Edge) obj;
return edge.src==src && edge.value==value && edge.weight==weight;
}
System.out.println("non e' ramo");
return false;
}
@Override
public String toString(){
return "["+src+"->"+value+" ("+weight+")]";
}
}
Here it's the main class that tests the result of the functions in the library In the last line I get this error: expected.get(0) is a String while result is an Edge and they can't be compared
public class GraphTests {
private static Graph<Integer> test_graph=new Graph<>();
public static void main(String[] args) throws GraphException {
test_graph.createGraph(false);
test_graph.createNode(1);
test_graph.createNode(5);
test_graph.createNode(7);
test_graph.createEdge(1,7,213);
test_graph.createEdge(1,5,13);
test_graph.createEdge(5,7,3);
test_graph.deleteEdge(1,5);
LinkedList<Edge> result=new LinkedList<>();
result=test_graph.getEdges(); //the results are correctly inserted in the linked list of edges
LinkedList<Edge> expected=new LinkedList<>();
expected.add(new Edge(1,7,213)); //here I am testing just the first Edge
System.out.println("equals ? "+expected.get(0)==result.get(0)); //the error is HERE
}
}
I think I tried everything but I still don't get it... Any help would be appreciated
Solution
Try this
var res = expected.get(0)==result.get(0);
System.out.println("equals ?"+res);
The plus (+) is executed before the equal (==) so it The compiler thinks you compare a string to an object The result of the plus (+) is a string
Answered By - Samer Aamar
Answer Checked By - Terry (JavaFixing Volunteer)