可变长度参数是否在Java中被视为数组? [英] Is a variable length argument treated as an array in Java?

查看:132
本文介绍了可变长度参数是否在Java中被视为数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,array由固定数量的元素组成,而variable length argument接受的传递数量与您传递的参数数量相同(相同类型).但是他们是一样的吗?我可以通过一个期望的地方吗?

As I understand an array consists of fixed number of elements and a variable length argument takes as many number of arguments as you pass (of the same type). But are they same? Can I pass one where the other is expected?

推荐答案

是的,如果您有一个带有varargs参数的方法,如下所示:

Yes, if you have a method with a varargs parameter like this:

public void foo(String... names)

您这样称呼它:

foo("x", "y", "z");

然后编译器将其转换为:

then the compiler just converts that into:

foo(new String[] { "x", "y", "z"});

names参数的类型是String[],可以像使用任何其他数组变量一样使用.请注意,它可以仍然是null:

The type of the names parameter is String[], and can be used just like any other array variable. Note that it could still be null:

String[] nullNames = null;
foo(nullNames);

请参见有关argargs的文档更多信息.

这不是不是意味着varargs可与数组互换-您仍然需要声明该方法来接受varargs.例如,如果您的方法声明为:

This does not mean that varargs are interchangeable with arrays - you still need to declare the method to accept varargs. For example, if your method were declared as:

public void foo(String[] names)

然后第一种调用它的方法将无法编译.

then the first way of calling it would not compile.

这篇关于可变长度参数是否在Java中被视为数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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