问题
What is the difference between these 4 method signatures, and why does the 4th not work?
public void main(String args[]) {... }
public void main(String[] args) {... }
public void main(String... args) {... }
public void main(String[] args[]) {... }
回答1:
The first three are equivalent.* The last one is equivalent to String[][] args
(i.e. an array of arrays), which doesn't match what Java requires for main
.
However, the idiomatic version is the second one.
* The third one is only valid from Java 5 onwards.
回答2:
String args[]
and String[] args
are exactly equivalent. The first form is the "C" form of array declaration, with the []
applied to the variable name. The second form is the preferred Java form, where the []
is (more logically) associated with the type name rather than the variable name. Java allows both forms interchangeably.
The third form appears to be a variable-length parameter list form, though I've never delved into that area.
The forth form is an abomination that only sneaks through the cracks of the spec and should never be used. My guess is that it specifies a 2-dimensional array, but one can't be sure without trying it.
Note that there's nothing sacred about public static main
. You can name any method main
and call it from anywhere. It's just that when you run a Java program from the command line the JAVA command looks for something of that name (with the usual parameter layout) as the entry point. Up until then main
is treated like any other method.
来源:https://stackoverflow.com/questions/8290492/variations-on-public-static-main-string-args