盘点JDK1.5的新特性(二)——可变参数

在JDK中提供的方法经常可以看见可以接受多个参数的形式,如Arrays.asList

asList public static <T> List<T> asList(T... a) Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.) This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray(). The returned list is serializable and implements RandomAccess. This method also provides a convenient way to create a fixed-size list initialized to contain several elements: List<String> stooges = Arrays.asList("Larry", "Moe", "Curly"); Parameters: a - the array by which the list will be backed Returns: a list view of the specified array --------------------------------------------------------------------------------
这样的内容是怎么实现的呢,看下面的一个例子:
package example; public class VariableParameter { public static void main(String[] args) { System.out.println(add(123, 123, 123)); } public static int add(int i,int... js){ for(int j : js) i += j; return i; } }

在add方法中可以看到,第一个参数是int i 而第二个参数形式为这样int... js ,int后面有三个点,这就是接收可变数量参数的写法,实际上,Java编译器会将第二个参数以数组的形式接受,也就是说int... js 也就类似于int[] js,所以在方法里面就可以把js当做数组来操作了。

值得注意的是:可变参数只能放在参数的最后面,否则会无法编译成功。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值