2013-08-21 27 views
1

我想让我自己的类的参数之一是一个数组。我可以做这个工作吗?使用类调用实例化新数组

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

我可以做这个工作吗?我想通过类似Node的方式来调用它(4,“Title”,[1,2,3])

+1

您已经编写所有的代码,为什么不你只需添加一个主体并测试它? – Grammin

+0

我做了,它不起作用。 –

回答

8

我想通过Node(4,“Title”,[1 ,2,3])

行不通的,因为[1, 2, 3]不是创建Java中的数组的一个有效途径,但你当然可以这样调用它:

Node node = new Node(4, "Title", new int[] { 1, 2, 3 }); 

或者您可能想要使用可变参数:

Node(int i, String title, int... links) 

这将让你称呼其为:

Node node = new Node(4, "Title", 1, 2, 3); 
+0

可变参数?那是什么意思。 –

+4

@ YKQ56:你问这个问题之前有没有搜索?快速搜索“varargs java”可立即为我提供相关文档。 –

+0

是的,我搜索,这些链接超出我的知识,以解释您的建议将需要几个小时。 –

1

是你can.By创建匿名数组这样

new Node(4, "Title", new int[]{1,2,3}); 
+0

这可以工作,但我不能让它wokr像这样 公共类graph1 { \t公共静态无效的主要(字串[] args){ \t \t ArrayList的网络=新的ArrayList (); \t \t \t web.add(0,(0,“google”,new int [] {1,2})); \t \t \t} } –

相关问题