我有一个类似的复杂结构
ArrayList<LinkedList<Struct>>
在我的主类中,我有两个嵌套类,如下
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函数
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
}
我从主功能传递这些值
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函数
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");
}
}
输出为
src=A dest=A rights=[]
src=A dest=V rights=[G]
src=B dest=B rights=[]
src=B dest=V rights=[G]
但预期输出是
src=A dest=A rights=[]
src=A dest=V rights=[T, G]
src=B dest=B rights=[]
src=B dest=V rights=[G]
我不明白为什么边缘(A,V(的权限被更新为(B,V(权限。当我只从主发送(A,V(时,我得到的值是正确的
src=A dest=A rights=[]
src=A dest=V rights=[T, G]
想了解为什么会发生这种情况以及如何解决?
List.clear((
clear((将遍历底层数组,并将每个条目设置为null。
使用rights.clear()
您已经删除了指向:-的引用
rights.add("T");
rights.add("G");
在图中,您必须为您的更改创建一个新的权限副本以显示,否则使用clear()
将从内存中删除所有现有引用。
更新addEdge方法:-
static void addEdge(Graph graph, String src, String dest, Set<String> rights) {
Set<String> copyRights = new HashSet<>(rights); //create a new copy of rights.
struct destStruct = new struct();
destStruct.setName(dest);
destStruct.setRights(copyRights);
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
}