为什么错了?我不能使用添加,我不确定如何使用。一些 java 文档说我需要 add(index,data) 但其他的只是 add(data) 并且编译器也支持它。我的数据类型有误。
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});
}
}
节点.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;
}
}
最佳答案
您忘记将 new Node(...)
包含在 ArrayList 的 add(...)
方法中,因为您没有添加以下组合一个 int、一个 String 和一个 int 数组到 ArrayList,而是要添加一个 Node 对象。为此,必须显式创建并添加 Node 对象:
web.add(new Node(0, "google", new int[]{1,2}));
关于java - 将自定义类与 ArrayLists 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18366479/