首页 > 解决方案 > 创建邻接列表图

问题描述

我正在尝试通过创建边缘类型的数组列表(包括源、目标、权重)来为图形创建邻接列表,如下面的代码所示:

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时我需要给出上述语句所以我不能直接添加元素?

标签: javaarraysarraylistdata-structuresgraph

解决方案


此代码声明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>();
    }

推荐阅读