This question should be fairly simple for any Java developer. I swear I looked at it, spending ~ 2 hours on it, but I canβt understand what is wrong with this code.
Basically, I implement the Karger minimum cut algorithm. This requires me to continue merging the nodes in the graph and then calculate the number of intersecting edges at the end (int value). This algorithm should be repeated n times, always from the initial schedule. My problem is that I cannot create a deep copy of my Graph object, and I cannot find the error.
I cut the code to just show the problem, and nothing more, but I still canβt understand what happened. Here is the code.
Node Class:
public class Node { public Integer Data; public Node() { Data = 0; } public Node(Node rhs) { Data = rhs.Data.intValue(); } public Node(Integer rhs) { Data = rhs.intValue(); } public void setNode(Integer rhs) { Data = rhs; }
Class Schedule:
public class Graph { public ArrayList<ArrayList<Node>> AdjList; public ArrayList<Node> NodeSet;
Main:
public class Main { public static void main(String[] args) { Node Five = new Node(5); Node Seven = new Node(7); Node One = new Node(1); Graph G = new Graph(); ArrayList<Node> L = new ArrayList<Node>(); L.add(Five); L.add(Seven); L.add(One); G.addNewAdjList(L); Graph R = new Graph(G); R.AdjList.get(0).get(1).setNode(19);
}
Output:
5: 19, 1,
5: 19, 1,
This type puzzles me, to be honest. I understand that Java is passed only by value, but objects are always represented by their reference. As far as I understand, my copy constructor for G should always make a deep copy: I go through each adjacency list and then make a deep copy of Node. I do not understand why calling .setNode () for the copied object also changes the original object (which has a different reference).
Previous answers like 1 seem to go in the same direction as me, what am I missing here ?: S
source share