I have a complex structure like
ArrayList<LinkedList<Struct>>
In my main class I have 2 nested classes as below
static class struct {
private String name;
Set<String> rights = new HashSet<String>();
//getters and setters
}
static class Graph {
ArrayList<LinkedList<struct>> adjListArray;
Graph() {
adjListArray = new ArrayList<>();
}
}
addEdge function
static void addEdge(Graph graph, String src, String dest, Set<String> rights) {
// code for creating a src block if it is not present and adding dest to it as below
struct destStruct = new struct();
destStruct.setName(dest);
destStruct.setRights(rights);
graph.adjListArray.get(getIndexOf(graph, src)).add(destStruct); // getIndexof is a function which will return the list index whose first element name is equal to src
}
I am passing these values from main function
public static void main(String args[]) {
Graph graph = new Graph();
Set<String> rights = new HashSet<String>();
rights.add("T");
rights.add("G");
addEdge(graph, "A", "V", rights);
rights.clear();
rights.add("G");
addEdge(graph, "B", "V", rights);
printGraph(graph);
}
printGraph function
static void printGraph(Graph graph) {
for (LinkedList<struct> list : graph.adjListArray) {
for (struct var : list) {
System.out.println(
"src=" + list.get(0).getName() + " dest=" + var.getName() + " rights=" + var.getRights());
}
System.out.println("\n");
}
}
The output is
src=A dest=A rights=[]
src=A dest=V rights=[G]
src=B dest=B rights=[]
src=B dest=V rights=[G]
but expected output is
src=A dest=A rights=[]
src=A dest=V rights=[T, G]
src=B dest=B rights=[]
src=B dest=V rights=[G]
I couldn't understand why rights of edge (A,V) got updated with the rights of rights of (B,V). When I send only (A,V) from main I am getting the values correctly as
src=A dest=A rights=[]
src=A dest=V rights=[T, G]
Wanted to understand why this is happening and how to resolve this?