【问题标题】:How do I initiate an array within object parameters in Java?如何在 Java 中的对象参数中启动数组?
【发布时间】:2019-07-16 20:44:12
【问题描述】:

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

public class Example {
    String[] words;

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

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

当我尝试编译它时,这给了我一个错误。 有没有办法在不首先在对象声明之外初始化数组的情况下做到这一点?

【问题讨论】:

  • 构造函数参数本身必须声明为String[] words,并且必须使用new String[]{...}来传递参数。
  • "当我尝试编译时出现错误" - 请包含 cpile 错误消息并突出显示导致编译错误的行。
  • public Example(words) {this.words = words;} 更改为public Example(String[] words) { this.words = words; } ,一切都应该是开箱即用的。请注意,您还授予包对 Example 类的 words 属性的访问权限。

标签: java arrays object parameters


【解决方案1】:

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

public class Example {
    String[] words;

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

您可以从 main 调用构造函数,而无需像这样初始化 String[] 数组:

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

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

【讨论】:

    【解决方案2】:

    您需要如下声明构造函数示例的参数类型,以消除构造函数中的编译错误。

    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】:

      没有看到其他人提到它,但由于您似乎对这门语言有些陌生,因此还值得一提的是,您可以在构造函数中使用 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 如果您有兴趣,请提供更多背景知识。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-11-22
        • 2011-02-17
        • 1970-01-01
        • 2020-06-09
        • 1970-01-01
        • 2016-10-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多