java - 创建邻接列表图
问题描述
我正在尝试通过创建边缘类型的数组列表(包括源、目标、权重)来为图形创建邻接列表,如下面的代码所示:
public class Main {
static class Edge{
int s;
int d;
int wt;
Edge(int src,int des,int weight)
{
this.s = src;
this.d = des;
this.wt = weight;
}
}
public static void main(String[] args) throws Exception
{
//creating array of arraylist of type edge
ArrayList<Edge>[] graph = new ArrayList[7];
//Doubt regarding this line ,as why is it essential?
graph[0] = new ArrayList<Edge>();
//creating edge object
Edge e = new Edge(0,1,10);
//adding it into arraylist
graph[0].add(e);
}
由于我创建了 edge 类型的 arraylist 数组,我想我可以直接添加到 arraylist 中,比如 graph[0].add(e) 而无需编写 graph[0] = new ArrayList();
但没有它就行不通。为什么当我的数组是arraylist时我需要给出上述语句所以我不能直接添加元素?
解决方案
此代码声明graph
为 7 的数组ArrayList
,其元素最初(与所有数组一样)设置为其默认值 -null
对于对象、0
整数、false
布尔值:
ArrayList<Edge>[] graph = new ArrayList[7];
您可以通过在下面添加此行来测试它,或者通过调试器逐步进行测试:
System.err.println(graph[0]); // prints "null"
您new ArrayList[7]
唯一为 ( ) 个对象数组保留的空间ArrayList
,但没有为ArrayLists
要添加的 7 个新对象保留空间。例如,这允许您将 的子类添加ArrayList
到您的数组中,或者为一些槽保留一个null
值,或者将相同的值添加ArrayList
到多个槽中。所有这些选项在某些情况下都很有用,因此编译器和语言不会创建空的新元素,除非您明确地这样做。我建议使用循环:
ArrayList<Edge>[] graph = new ArrayList<>[7];
for (int i=0; i<graph.length; i++) {
graph[i] = new ArrayList<Edge>();
}
推荐阅读
- html - 显示/折叠事件上菜单高度的 CSS 过渡
- pandas - Snipped Tails - 查找所有缺少空值的表尾
- javascript - 如何在javascript中从0到10分钟运行计时器?
- ansible - 将具有不同 ansible_user 的重复名称添加到 add_host 动态清单的问题
- php - 更改 Laravel 5.5.46 应用程序的应用程序路径
- python - 在条件下突出显示单元格
- javascript - JavaScript + UNIX 中的转义字符问题
- html - 无法旋转 3d 立方体
- deep-learning - 在 CIFAR 数据集上具有铰链损失的 Densenet
- robotframework - 如何在机器人框架中将浮点数转换为字符串