【问题标题】:How do I add a null object to an ArrayList inside an ArrayList如何将空对象添加到 ArrayList 内的 ArrayList
【发布时间】:2015-04-22 23:43:12
【问题描述】:

我正在尝试使用邻接矩阵结构来表示 Ad Hoc 网络。为此,我在另一个 ArrayList 中创建了一个 ArrayList。

当我向图中添加一个新顶点时,我创建了一个新的 ArrayList(在一个超级 ArrayList 内),然后我有一个循环来为每个 ArrayList 添加一个新的空对象,但是 ArrayLists 的大小不会正确增加我不知道为什么。

这是我的代码:

public class Matrix {

public ArrayList<ArrayList<Edge>> graph;
public ArrayList<Vertex> verticies;
public ArrayList<Edge> edges;

public Matrix() {
    graph = new ArrayList();
    verticies = new ArrayList();
    edges = new ArrayList();
}

public Matrix(ArrayList<Vertex> verticies, ArrayList<Edge> edges) {

    this.verticies = verticies;
    this.edges = edges;      
}

public void addVertex(Vertex v) {
    verticies.add(v);
    graph.add(new ArrayList());

    for(int i=0; i<graph.size()-1; i++ ) {
        graph.get(i).add(null);
    }
}

任何帮助将不胜感激。

【问题讨论】:

    标签: java arraylist graph


    【解决方案1】:

    graph 的初始大小是0,所以addVertex() 中的for 循环运行的次数比它应该运行的少一倍:

    public void addVertex(Vertex v) {
        verticies.add(v);
        graph.add(new ArrayList()); // graph now has size 1
    
        for (int i = 0; i < graph.size() - 1; i++) { // i = 0, 0 < 0 is false       
            graph.get(i).add(null); // this is not executed for the last added list
        }
    }
    

    下次您调用addVertex() 时,它会将null 添加到之前的ArrayLists,但不会添加到您刚刚添加的那个。

    所以你可能应该这样做:

    for (int i = 0; i < graph.size(); i++)
    

    即使使用此修复程序,请注意,如果您调用 addVertex() 5 次,您将得到如下内容:

    index             ArrayList
      0      [null, null, null, null, null]
      1      [null, null, null, null]
      2      [null, null, null]
      3      [null, null]
      4      [null]
    

    这可能不是你想要的。更好的方法是首先添加所有顶点

    public void addVertex(Vertex v) {
        this.vertices.add(v);
    }
    

    然后为具有适当大小的邻接矩阵创建ArrayLists:

    public void initializeAdjacencyMatrix() {
        int n = this.vertices.size();
        for (int i = 0; i < n; i++) {
            List<Edge> edges = new ArrayList<>(Collections.nCopies(n, null));
            graph.add(edges);
        }
    }
    

    另外,您在实例化 ArrayLists 时使用了原始类型。这不是一个好习惯。您应该改用菱形运算符。例如:

    graph = new ArrayList<>();
    graph.add(new ArrayList<>());
    

    【讨论】:

    • 感谢您的帮助,但是 ArrayLists 现在每次都会减小 1(例如,如果 graph.size() 为 5,graph.get(1).size() 为 5,graph .get(2).size() 是 4 等等。真让我困惑 D:
    • @AlexGlassman 那是因为您每次创建新列表时都会将null 添加到所有以前的列表中。所以最先创建的将有更多的nulls。我用处理这个问题的建议更新了答案。
    • 不错的解决方法,但是我必须将内部 ArrayLists 的类型更改为 Object。有什么办法吗?
    • @AlexGlassman 是的,如果您使用的是 Java 7,则需要将类型参数传递给 nCopies()new ArrayList&lt;&gt;(Collections.&lt;Edge&gt;nCopies(n, null));
    【解决方案2】:

    在这一行:

    for(int i=0; i<graph.size()-1; i++ ) {
    

    删除-1。因为图形大小为1时-1i不会小于0,所以循环不会运行。如果循环没有运行,那么添加 null 值的代码将无法运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-26
      • 2019-02-18
      • 1970-01-01
      • 2017-12-12
      相关资源
      最近更新 更多