java可变参数 和数组的区别,Java可变长度参数与数组,只是语法糖?

I am taking a Data Structures and Algorithms course for fun at a local community college. The course's textbook is Y. Daniel Liang's Introduction to Java Programming, 10th Edition. The book, itself, is pretty solid.

In dealing with Java.util.Arrays, Liang mentions Java's "variable-length" parameter. He writes (p. 265):

Java treats a variable-length parameter as an array. You can pass an

array or a variable number of arguments to a variable-length

parameter. When invoking a method with a variable number of arguments,

Java creates an array and passes the arguments to it.

An example being:

public static void (int... toes) {

//... some code

}

However, Liang never explains the origin or advantage of the variable-length parameter. If, as Liang says, the variable-length parameter is "converted" to an array, what is their advantage? Is there a software design pattern or engineering goal that is facilitated by the variable length parameter?

In other words, what does the above code snippet offer that is not offered by the below:

public static void (int[] toes) { // ...

解决方案

In Java, varargs are a syntactical sugar for creating an array when calling a method. For example, these two calls are equivalent:

void foo(String... args) { ... }

foo("hello", null, "world", xyz); // Java 1.5+

foo(new String[]{"hello", null, "world", xyz}); // All versions of Java

Varargs doesn't make anything new possible (by definition of syntactic sugar), but it reduces verboseness and makes some constructs much more agreeable to implement. For example, some of my favorite uses of vararg include: PrintStream.printf(), String.format(), Method.invoke().

Other good applications of varargs:

// This one is in the Java standard library

Collections: void addAll(Collection super T> c, T... elements);

// Custom examples

int max(int... nums);

void doOperation(File x, String y, SomeEnum options...);

Additionally, Java's varargs bring the language up to parity with the vararg support in C, Python, JavaScript, and other languages. So if a frequently recurring design (such as max()) works best with varargs, Java is no longer the odd language that requires an uglier implementation.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值