为什么Java主要使用变长参数列表? [英] Why doesn't Java's main use a variable length argument list?

查看:91
本文介绍了为什么Java主要使用变长参数列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Java main 声明的语法有疑问:

I have a question about the syntax of the Java main declaration:

public static void main (String[] args)

因为你可以传递一个可变数量的调用main函数时的字符串,不应该是变量长度参数列表而不是数组吗?为什么使用字符串参数列表对此方法进行命令行调用甚至可以工作? (除非有幕后处理用字符串列表构建一个数组,然后将该数组传递给main方法......?)主要声明不应该更像这样......? -

Since you can pass a variable number of Strings when invoking the main function, shouldn't this be a variable length argument list rather than an array? Why would a command-line invocation of this method with a list of string parameters even work? (Unless there is behind-the-scenes processing that builds an array with the list of strings and then passes that array to the main method...?) Shouldn't the main declaration be something more like this...? -

public static void main(String... args) 


推荐答案

main(String ... args) main(String [] args)实际上是一回事:你得到的是一个 String 数组。 varargs只是调用者的语法糖。

main(String... args) and main (String[] args) are effectively the same thing: What you're getting is a String array. The varargs is just syntactic sugar for the caller.

我想你从来没有从代码中调用 main(),当引入varargs时,它没有被改装。

I guess as you never call main() from code, it wasn't retrofitted when varargs were introduced.

编辑:实际上,刮开最后一句话。 main(String ... args)当然是完全有效的语法。这两种风格完全可以互换。这很好用:

Edit: Actually, scratch that last sentence. main(String... args) is perfectly valid syntax, of course. The two styles are completely interchangeable. This works just fine:

public class Test {

    public static void main(String... args) {
        System.out.println("Hello World");
    }

}

这篇关于为什么Java主要使用变长参数列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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