如何在Java中的对象参数中初始化数组?

时间:2019-02-22 17:40:22

标签: java arrays object parameters

我正在尝试制作一个程序,但语法有问题。我试图创建一个数组作为对象的参数,但是语法有问题。

public class Example {
    String[] words;

    public Example(words) {
        this.words = words;
    }
}

public class Construction {
    Example arrayExample = new Example({"one", "two", "three"});
}

当我尝试编译它时,这给了我一个错误。 有没有一种方法,而无需首先在对象声明之外初始化数组?

4 个答案:

答案 0 :(得分:3)

您在参数化构造函数的参数中缺少字符串数组words的数据类型。为了匹配私有数据成员数组String [] words的数据类型,它必须为String[] words。像这样:

public class Example {
    String[] words;

    public Example(String[] words) {
        this.words = words;
    }
}

您可以从主结构调用构造函数,而无需初始化String[]数组,如下所示:

public class Construction {
    Example arrayExample = new Example(new String[]{"one", "two", "three"});
}

这是什么,它在运行时实例化一个对象并将其作为参数直接发送到构造函数。

答案 1 :(得分:0)

尝试一下:

new Example(new String[] {"one", "two", "three"});

您可以使用此语法动态填充数组,在花括号之间提供值。

答案 2 :(得分:0)

您需要按以下方式声明“构造函数示例”的Parameter类型,以消除构造函数中的编译错误。

Example(String[] words){
  this.words = words;
}

要将数组作为参数传递,您需要像这样调用数组的构造函数

new Example(new String[]{"I am a string","I am another string"});

或使用变量声明它,并像这样使用它。

String[] argument = {"I am a string","I am another string"};
new Example(argument);

有一个很好的解释in this answer

答案 3 :(得分:0)

没有看到其他人提及它,但是由于它似乎是该语言的新手,因此值得一提的是,您可以使用varargs语法代替数组作为构造函数:

public Example(String... words) {
    this.words = words;
}

这仍然允许您传递数组,但也允许您使用0个或多个普通String参数调用构造函数:

new Example("no", "need", "to", "pass", "an", "array");
new Example(); // same as empty array and works perfectly fine
new Example("one_word_is_ok_too");
new Example(new String[]{"can","use","arrays","as","well"});

Here's(如果您有兴趣的话)。

相关问题