search

Home  >  Q&A  >  body text

Java中不能在声明数组大小的同时初始化的根本原因是什么?

找了一下发现网上只说就这么定义的,哪位大神能帮忙解释一下根本原因?
是不是能从虚拟机的角度解释一下?
谢谢啦!

eg.

String s[] = new String[] {"1","2","3"};正确
String s[] = {"1","2","3"};正确
String s[] = new String[3] {"Zero","One","Two"};错误
PHP中文网PHP中文网2767 days ago666

reply all(3)I'll reply

  • 阿神

    阿神2017-04-17 17:27:34

    Array initialization is to obtain the fixed capacity of the array. The
    {"","",""} method can obtain the fixed capacity of the array and assign a value to each element.

    new String[3] can also tell the compiler the fixed capacity of the array, and by the way, set each element to null,

    However, the two methods of standardizing the fixed capacity of the array at the same time may cause conflicts in syntax,

    For example, new String[4]{"","",""},

    So in order to avoid such ambiguity, this way of writing that also regulates the array capacity should be prohibited from a grammatical perspective

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 17:27:34

    The grammar is stipulated in this way. . .
    It has nothing to do with virtual machines

    https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.10.1

    reply
    0
  • 高洛峰

    高洛峰2017-04-17 17:27:34

    The array applies for a fixed size memory area

    reply
    0
  • Cancelreply