使用ArrayLists的自定义类

时间:2013-08-21 19:54:51

标签: java arraylist

为什么这是错的?我不能使用添加,我不知道如何。一些java文档说我需要添加(索引,数据),但其他只是添加(数据),编译器也支持。我的数据类型出错。

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;
        }
    }

5 个答案:

答案 0 :(得分:4)

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

web.add(new Node(0, "google", new int[]{1,2}));

答案 1 :(得分:3)

使用此:

web.add(new Node(0, "google", new int[] {1, 2}));

答案 2 :(得分:3)

你需要像这样制作节点

Node node = new Node(i, title, links);
web.add(node);

答案 3 :(得分:2)

你有一个节点的arraylist,但是正在尝试添加一堆随机变量。您需要使用这些变量来创建一个Node,然后添加它。

web.add(new Node(0, "google", new int[]{1,2}));

答案 4 :(得分:0)

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

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

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