向对象内的指针数组添加元素

时间:2014-11-19 19:40:21

标签: java arrays

class Family
{
    String name;
    Family[] siblings;
    Family mother;
    Family father;
    Family spouse;
}
public class Pointer
{
    public static void main(String args[])
    {
        Family saun = new Family();
        saun.name = "Saun Bladow";

        Family shannon = new Family();
        shannon.name = "Shannon Bladow";

        Family kailey = new Family();
        kailey.name = "Kailey Bladow";

        Family kyle = new Family();
        kyle.name = "Kyle Bladow";
        saun.siblings = {shannon, kailey, kyle};
    }
}

此代码导致此错误

illegal start of expression
        saun.siblings = {shannon, kailey, kyle};
                        ^

我知道这段代码会起作用

        Family[] siblings = new Family[3];
        siblings[0] = shannon;
        siblings[1] = kailey;
        siblings[2] = kyle;
        saun.siblings = siblings;

但考虑到这个家族树有多大,我宁愿使用第一种方法,但我无法弄清楚如何让它工作

1 个答案:

答案 0 :(得分:1)

这取决于它自己的语言语法,但在C#中你可以做这样的事情。我相信你在其他语言中也有类似的语法,基本上你创建一个新的数组并填充它。

saun.siblings = new Family [] {shannon, kailey, kyle};