在构造函数中使用数组常量时出现编译器错误 [英] Getting compiler error while using array constants in the constructor

查看:32
本文介绍了在构造函数中使用数组常量时出现编译器错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class Sonnet29 implements Poem {
    private String[] poem;
    public Sonnet29() {
        poem = { "foo", "bar" , "baz"};
    }
    @Override
    public void recite() {
      //...
    }
}

poem = { "foo", "bar" , "baz"}; 给出编译错误.

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

Any specific reason why this is not allowed? How do I initialize a String array with array constants?

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

Thank you folks for your answers. Now I'm clear what is allowed and what is NOT. But can I ask you why this is NOT allowed?

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

谷歌搜索后,我发现了这个链接,在那里,它被告知像这样的编码使编译器含糊不清 - 宠物应该是字符串数组还是对象数组.但是从声明中可以很好的判断出它是一个String数组,对吧???

After googling a bit, I found this link, where in, it is told that coding like this leaves the compiler in ambiguity - whether the pets should be array of Strings or array of Objects. However from the declaration, it can very well figure out that it is a String array, right???

推荐答案

这将满足您的需求:

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

仅在创建数组的新实例时才允许初始化列表.

Initialization lists are only allowed when creating a new instance of the array.

这篇关于在构造函数中使用数组常量时出现编译器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆