为什么我们不能只使用数组而不是varargs? [英] Why can't we just use arrays instead of varargs?

查看:91
本文介绍了为什么我们不能只使用数组而不是varargs?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在学习android(doInBackground(Type... params))时碰到了varargs SO 帖子阐明了它的用法

I just came across varargs while learning android(doInBackground(Type... params)) ,SO posts clarified the use of it

我的问题是为什么我们不能只使用数组而不是varargs

My question is why can't we just use Arrays instead of varargs

public void foo(String...strings) {  }

我可以通过将可变数量的参数打包到数组中并将其传递给诸如此类的方法来替换这种类型的调用

I can replace this type of a call by packing my variable number of arguments in an array and passing it to a method such as this

public void foo(String[] alternativeWay){  }

Java中的main(String[] args)也会使用varargs,如果没有,我们如何将运行时参数传递给它

Also does main(String[] args) in java use varargs , if not how are we able to pass runtime parameters to it

请提出varargs的优点或用法,关于varargs

Please suggest the benefits or use of varargs and is there there anything else important to know about varargs

推荐答案

两者之间的唯一区别

foo(String... strings)

foo(String[] strings)

用于呼叫代码.考虑一下这个呼叫:

is for the calling code. Consider this call:

foo("a", "b");

这对foo的第一个声明有效,并且编译器将在执行时发出代码以创建一个包含对"a""b"的引用的数组.不过,它对foo的第二个声明无效无效,因为它不使用varargs.

That's valid with the first declaration of foo, and the compiler will emit code to create an array containing references to "a" and "b" at execution time. It's not valid with the second declaration of foo though, because that doesn't use varargs.

无论哪种情况,调用方明确地创建数组都是可以的:

In either case, it's fine for the caller to explicitly create the array:

for(new String[] { "a", "b" }); // Valid for either declaration

Java中的main(String [] args)也使用varargs,如果不是,我们如何向其传递运行时参数

Also does main(String[] args) in java use varargs , if not how are we able to pass runtime parameters to it

写为main(String[] args)时不是.如果您编写main(String... args),则可以.不过,这与JVM的处理方式无关,因为 JVM初始化会创建带有命令行参数的数组.仅当您编写自己的代码以显式调用main时,这才有所不同.

When it's written as main(String[] args) it doesn't; if you write main(String... args) then it does. It's irrelevant to how the JVM treats it though, because the JVM initialization creates an array with the command line arguments. It would only make a difference if you were writing your own code to invoke main explicitly.

这篇关于为什么我们不能只使用数组而不是varargs?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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