gpt4 book ai didi

java - 构造函数未初始化字段?影子?

转载 作者:行者123 更新时间:2023-12-01 22:23:11 25 4
gpt4 key购买 nike

我正在尝试创建一个邻接列表,为此我需要创建一个链接列表的数组列表。当我这样做时,这个 cityList 的大小不会更改为构造函数中传递的大小。我觉得这可能是由于阴影造成的,但我不确定阴影是如何工作的,或者是否发生了这种情况:

import java.util.*;

public class AdjList{

public ArrayList<EdgeList> cityList;

public AdjList(int size){
this.cityList = new ArrayList<EdgeList>(size+1);
}

public void add(int vertex, int edge, int distance, float price){
cityList.get(vertex).add(edge, distance, price);
}
}

在主课中我所做的:

AdjList flights = new AdjList(numCities);

最佳答案

当您使用 new ArrayList<EdgeList>(size+1); 创建列表时, size+1是列表的初始容量,而不是其大小。在将元素添加到列表之前,大小将保持为 0。

添加 EdgeList将元素添加到列表中:

cityList.get(vertex).add(edge, distance, price);

没有任何意义,因为它强制您初始化索引 0 中列表的所有元素。至vertexEdgeList实例。否则cityList.get(vertex)抛出异常。

如果您希望能够通过顶点访问元素,也许 Map<Integer,EdgeList>将是一个更好的结构:

this.cityList = new HashMap<Integer,EdgeList>();
...
EdgeList el = new EdgeList();
cityList.put(vertex,el);
el.add(edge, distance, price);

关于java - 构造函数未初始化字段?影子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29292954/

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