Getting compiler error while using array constants in the constructor

后端 未结 3 1775
面向向阳花
面向向阳花 2020-12-05 22:30
public class Sonnet29 implements Poem {
    private String[] poem;
    public Sonnet29() {
        poem = { \"foo\", \"bar\" , \"baz\"};
    }
    @Override
    publ         


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-05 23:27

    {"cat", "dog"}
    

    Is not an array, it is an array initializer.

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

    This can be seen as an array 'constructor' with two arguments. The short form is just there to reduce RSI.

    They could have given real meaning to {"cat", "dog"}, so you could say things like

    {"cat", "dog"}.length
    

    But why should they make the compiler even harder to write, without adding anything useful? (ZoogieZork answer can be used easily)

提交回复
热议问题