2

Why is this wrong? I can't use add, I am not sure how to. Some java documentation says I need to have add(index,data) but others are just add(data) and the compiler is support that as well. It is having an error with my data type.

import java.util.*;
public class graph1 {

    public static void main (String[] args){
        ArrayList<Node> web = new ArrayList<Node>();    
        web.add(0, "google", new int[]{1,2});

    }
}

Node.java:

 public class Node {
        int i;
        String title;
        int[] links;    

        Node(int i, String title, int[] links){
            this.i = i;
            this.title = title;
            this.links = links;
        }
    }
4

5 回答 5

3

您忘记包含new Node(...)在 ArrayList 的add(...)方法中,因为您没有将 int、String 和 int 数组的组合添加到 ArrayList,而是添加了 Node 对象。为此,必须显式创建 Node 对象,然后添加:

web.add(new Node(0, "google", new int[]{1,2}));
于 2013-08-21T19:56:12.230 回答
2

用这个:

web.add(new Node(0, "google", new int[] {1, 2}));
于 2013-08-21T19:56:21.930 回答
2

你需要像这样制作节点

Node node = new Node(i, title, links);
web.add(node);
于 2013-08-21T19:57:17.407 回答
1

您有一个节点数组列表,但正在尝试添加一堆随机变量。您需要使用这些变量来创建一个节点,然后添加它。

web.add(new Node(0, "google", new int[]{1,2}));
于 2013-08-21T19:56:40.530 回答
-1

必须实例化您的自定义类才能将其添加到 ArrayList。为此,请使用web.add(new Node(0, "google", new int[]{1,2}));.

在您的情况下,您使用web.add(0, "google", new int[]{1,2});了 java 编译器理解为您试图一次添加 3 个对象,因此编译器抱怨您的代码有问题。

此外,如果您需要对数组进行排序,您应该考虑实现(覆盖)自定义compare(o1, o2) ,因为默认的Collections.sort(list)不知道如何正确排序您的对象。

于 2013-08-21T20:18:19.650 回答