如何在Java中的对象参数中启动数组



我正在尝试制作一个程序,并且在语法上遇到麻烦。我正在尝试创建一个数组作为对象的参数,但是我在语法上遇到了麻烦。

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

当我尝试编译时,这给了我一个错误。有没有办法这样做,而不先初始化对象声明之外的数组?

在参数化构造函数的参数中缺少字符串数组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"});
}

这是在运行时实例化对象并将其作为参数直接发送给构造函数。

将其直接发送为参数。

您需要在下面声明构造函数的参数类型,以删除构造函数中的编译误差。

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

这个答案中有一个很好的解释。

没有看到其他人提及它,但是由于您对语言有些新鲜,因此值得一提的是,您可以使用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"});

如果您有兴趣,这里还有一些背景。

最新更新