【问题标题】:Getting compiler error while using array constants in the constructor在构造函数中使用数组常量时出现编译器错误
【发布时间】:2011-03-05 22:34:17
【问题描述】:
public class Sonnet29 implements Poem {
    private String[] poem;
    public Sonnet29() {
        poem = { "foo", "bar" , "baz"};
    }
    @Override
    public void recite() {
      //...
    }
}

poem = { "foo", "bar" , "baz"}; 行出现编译错误。

不允许这样做的任何具体原因? 如何用数组常量初始化 String 数组?

编辑:谢谢大家的回答。现在我很清楚什么是允许的,什么是不允许的。 但是我能问你为什么这是不允许的吗?

String[] pets;
pets = {"cat", "dog"};

在谷歌上搜索了一下,我发现了这个link,在哪里,它被告知这样的编码会使编译器变得模棱两可——宠物应该是字符串数组还是对象数组。但是从声明中可以很好的判断出它是一个String数组,对吧???

【问题讨论】:

  • 如果是常量,那么poem不应该在构造函数中初始化。
  • @True Soft:我只是想用一些常量来“初始化”对象状态。同意。如果诗歌被声明为 STATIC,private static String[] 诗歌 = { "foo", "bar" , "baz"};它工作正常。
  • @HanuAthena,不管成员是不是static,这里的问题是数组初始化器只允许在声明中(§8.3,§9.3,§14.4),或作为数组创建表达式的一部分(第 15.10 节)。因此,如果没有static,如果您在现场执行此操作,private String[] poem = { "foo", "bar" , "baz"}; 也将起作用

标签: java arrays compiler-errors


【解决方案1】:
{"cat", "dog"}

不是一个数组,它是一个数组初始化器。

new String[]{"cat", "dog"}

这可以看作是一个带有两个参数的数组“构造函数”。简短的形式只是为了减少 RSI。

它们可以赋予 {"cat", "dog"} 真正的含义,所以你可以说类似

{"cat", "dog"}.length

但是为什么不添加任何有用的东西就让编译器更难编写呢? (ZoogieZork 回答可以轻松使用)

【讨论】:

    【解决方案2】:

    来自Java language specification

    可以在声明中指定数组初始值设定项,或作为数组创建表达式的一部分(第 15.10 节),创建数组并提供一些初始值

    简而言之,这是合法的代码:

    private int[] values1 = new int[]{1,2,3,4};
    private int[] values2 = {1,2,3,4}; // short form is allowed only (!) here
    
    private String[][] map1 = new String[][]{{"1","one"},{"2","two"}};
    private String[][] map2 = {{"1","one"},{"2","two"}}; // short form
    
    List<String> list = Arrays.asList(new String[]{"cat","dog","mouse"});
    

    这是非法的:

    private int[] values = new int[4];
    values = {1,2,3,4}; // not an array initializer -> compile error
    
    List<String> list = Arrays.asList({"cat","dog","mouse"}); // 'short' form not allowed
    

    【讨论】:

      【解决方案3】:

      这将满足您的需求:

      public Sonnet29() {
          poem = new String[] { "foo", "bar", "baz" };
      }
      

      只有在创建数组的新实例时才允许初始化列表。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-08-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多