Steven Meow De Claude Steven Meow De Claude - 26 days ago 8
Java Question

Java arraylist replacement value

I trying to replace the value in the arraylist of edge under the updateEdge() method.

At If statement, the value of the edge.a.name and edge.b.name matches my source and dest value but somehow it doesn't enter the IF condition.

What I found out is this, edge.a = Node@55f96302 and a.name = Node@55f96302.

What I know this when I print out the node address, both does not match.

private ArrayList<Node> nodes = new ArrayList<Node>();
private ArrayList<Edge> edges = new ArrayList<Edge>();

//add new node
public void addNode(String nodeName)
{
Node node = new Node(nodeName);
nodes.add(node);
}

//add edge
public void addEdge(String source, String dest, String weight)
{
Node a, b;
a = new Node(source);
b = new Node(dest);
Double w = Double.parseDouble(weight);

Edge edge = new Edge(a, b, w);
edges.add(edge);
}

//Check index of the node
public int indexOfNode(String name)
{
for (int i = 0; i < nodes.size(); i++)
{
if(nodes.get(i).name.equals(name))
{
return i;
}
}

return -1;
}
//update edge
public void updateEdge(String source, String dest, String weight)
{
Node a, b;
a = nodes.get(indexOfNode(source));
b = nodes.get(indexOfNode(dest));


Double w = Double.parseDouble(weight);

for(int i = 0; i < edges.size(); i++)
{
Edge edge = edges.get(i);

if(edge.a.name == a.name && edge.b.name == b.name)
{
edge.weight = w;
}
}
}

Answer

a String is an object, when you compare two objects in java by using the == operator, you compare their hashcode and class, hence the 'Node' and 55f96302. An int or double (for instance) are primitive types and hence can be compared with the == operator. They actually have to, seeing as how they don't have any methods for comparison since they are not objects (Integer and Double are their class counterparts).

In order to compare two strings based on their character array values, you will need to use the .equals() method:

edge.a.name.equals(a.name)