在Java中使用省略号(...)? [英] Use of ellipsis(...) in Java?

查看:526
本文介绍了在Java中使用省略号(...)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看一些代码并看到以下表示法。我有点不确定这三个点是什么意思,你称之为什么。

I was looking through some code and saw the following notation. I'm somewhat unsure what the three dots mean and what you call them.

void doAction(Object...o);

谢谢。

推荐答案

这意味着此方法可以接收多个Object作为参数。为了更好地低估,请从此处:

It means that this method can receive more than one Object as a parameter. To better understating check the following example from here:


省略号(...)标识可变数量的参数,并在以下求和方法中演示

The ellipsis (...) identifies a variable number of arguments, and is demonstrated in the following summation method.



static int sum (int ... numbers)
{
   int total = 0;
   for (int i = 0; i < numbers.length; i++)
        total += numbers [i];
   return total;
}




用尽可能多的逗号调用求和方法根据需要分隔整数
参数 - 在JVM的限制范围内。一些例子:总和
(10,20)和总和(18,20,305,4)。

Call the summation method with as many comma-delimited integer arguments as you desire -- within the JVM's limits. Some examples: sum (10, 20) and sum (18, 20, 305, 4).

这是非常有用,因为它允许你的方法变得更抽象。从SO中查看这个很好的示例,用户是否利用了...用来创建一个用Java连接字符串数组的方法的表示法。

This is very useful since it permits your method to became more abstract. Check also this nice example from SO, were the user takes advantage of the ... notation to make a method to concatenate string arrays in Java.

另一个例子来自 Java 5中的变量参数方法

public static void test(int some, String... args) {
        System.out.print("\n" + some);
        for(String arg: args) {
            System.out.print(", " + arg);
        }
    }

如评论部分所述:


另请注意,如果函数传递的是与barargs参数不同的
类型的其他参数,则vararg参数应为最后的
参数在函数声明中 public void test(Typev ... v,
Type1 a,Type2 b)
public void test(Type1 a,Typev ... v
recipientJids,Type2 b)
- 非法。仅公开无效测试(Type1 a,
Type2 b,Typev ... v)

这篇关于在Java中使用省略号(...)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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