addMany(E ... element)方法参数中的E ...是什么意思?

时间:2015-11-12 03:16:28

标签: java netbeans methods elements

如果有人能够解释这个addMany方法中E ...的意思,那将非常感激。 示例代码:

    /**
     * Add a variable number of new elements to this ArrayBag
     *
     * @param elements A variable number of new elements to add to the ArrayBag
     */
    public void addMany(E... elements) {
        if (items + elements.length > elementArray.length) {
            ensureCapacity((items + elements.length) * 2);
        }

        System.arraycopy(elements, 0, elementArray, items, elements.length);
        items += elements.length;
    }

1 个答案:

答案 0 :(得分:1)

这称为变量参数。它允许方法接受零个或多个参数。如果我们不知道参数的计数,那么我们必须在方法中传递它。作为一个变量参数的优点是我们不必提供重载方法,因此代码更少。

<强>实施例

class Sample{  

 static void m(String... values){  
  System.out.println("Hello m");  
  for(String s:values){  
   System.out.println(s);  
  }  
 }  

 public static void main(String args[]){  

 m();//zero argument   
 m("hello");//one argument   
 m("I","am","variable-arguments");//three arguments  
 }}
  

使用变量参数后,您必须在下面考虑   分。

  • 方法中只能有一个变量参数。
  • 变量参数必须是最后一个参数。

<强>实施例

void method(Object... o, int... i){}//Compile  error
void method(int... i, String s){}//Compile  error