gpt4 book ai didi

java - 将ArrayList的内容放入PriorityQueue Java问题

转载 作者:行者123 更新时间:2023-12-02 02:53:23 24 4
gpt4 key购买 nike

我有以下代码导致了问题:

List<Node> tempList=new ArrayList<Node>(); //baseline
//creation of another temporary list of type Node for temporary storage
List<Node> tempList2=new ArrayList<Node>();

List<Node> temp = Adjacency_List.get(current.dest);
for(Node node: temp){
//testing
System.out.print(current.dest + " - " + node.dest);
System.out.println("\t\t("+Main.getEdge(current, node)+")");

for(int i=0; i<tempList.size(); i++){
//copying nodes from tempList into tempList2
tempList2.add(tempList.get(i));
System.out.println("TEMP LIST2 : "+tempList2.size());
}

tempList2.add(node);
System.out.println("TEMP LIST2 SIZE : "+tempList2.size());
cost=tempCost;
cost+=Main.getEdge(current, node);
n=new Node(tempList2, cost);
pq.add(n);
tempList2.clear();
}

此代码的基本目标是获取当前节点的子节点(通过使用 current.dest),并且对于 temp 中的每个节点,它将 tempList 的内容复制到 tempList2 中(tempList 也包含节点)。当 tempList2 的内容添加到优先级队列 pq (pq.add(n)),然后使用 tempList2.clear() 清除后,就会出现问题。优先级队列pq 中tempList2 的内容也被该行清除。有没有办法可以清除 tempList2 数组列表的内容,而无需同时清除优先级队列中 tempList2 的内容(之前通过使用行 pq.add(n); 添加到优先级队列)?

最佳答案

是的,这是可能的。

解决方案1

添加列表的副本而不是原始列表本身。 clear() 原件后,副本将保持不变。改变

n = new Node(tempList2, cost);

n = new Node(new ArrayList<>(tempList2), cost);

解决方案2

创建一个新列表而不是在每次迭代中复制和清除相同列表可能会更好(对于效率和可读性)。删除

tempList2.clear();

然后移动

List<Node> tempList2 = new ArrayList<Node>();

到第一个循环的主体,以便您在每次迭代中创建一个新列表。

关于java - 将ArrayList的内容放入PriorityQueue Java问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43454349/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com