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

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

问题描述

据我所知,array 由固定数量的元素组成,而 可变长度参数 接受与您传递的参数(相同类型)一样多的参数.但它们是一样的吗?我可以在另一个预期的地方通过一个吗?

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);

请参阅有关可变参数的文档更多信息.

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

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天全站免登陆