简体   繁体   中英

Why don't we have to provide parentheses when initializing an array object in Java?

I'm learning Java from the ground up right now, and one thing I found interesting was that most more complex data structures must be created in this fashion:

ArrayList<String> list = new ArrayList<String>();

On the other hand, one can simply initialize a string by typing

String[] str_array = new String[10];

Why is it not necessary to provide the parentheses usually associated with calling the constructor when initializing an array? Was this just a stylistic choice? It would be awesome if someone with a better understanding of the JVM could offer some insight to sate my curiosity.

The difference between object creation and array creation is this:

  • normal classes have constructors that are called.
    • The parentheses in new ArrayList<String>() indicates the constructor call.
    • Even if a constructor has no arguments, the parentheses still have to be present (the same as in a method call without parameters).
  • array classes on the other hand have no constructor
    • Although arrays are objects, their classes are created by the JVM and are therefore subject to special handling that other classes cannot have
    • Initializing the array happens as side effect of the anewarray , multianewarray and newarray bytecode instructions.

That array classes have no constructors can be demonstrated by executing

System.out.println(int[].class.getConstructors().length);

which returns 0.


In the end, this boils down to decisions the language designers made more than 20 years ago and that were influenced by design decision from other existing languages (like C++).

Arrays can't be created in a same way as creating an ArrayList. As user207421 told , "Arrays are designed to initialize in such a way by using [] ". (eg)

ArrayList aList = new ArrayList(); // It is valid

Arrays aArr = new Arrays();// It is invalid. Since there is no public constructor in java.util.Arrays

Source Code : http://hg.openjdk.java.net/jdk8u/jdk8u/jdk/file/be44bff34df4/src/share/classes/java/util/Arrays.java

C & C++ Languages uses the same [] for initialize an array. So that Java also following.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM