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

What does E... in the addMany(E... element) method argument mean?

如果有人能解释 E... 在此 addMany 方法中的含义,我们将不胜感激。 示例代码:

    /**
     * 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;
    }

这称为可变参数。它允许方法接受零个或多个arguments.If我们不知道参数的数量然后我们必须通过这在 method.As 可变参数的一个优点是我们不必提供重载方法,因此代码更少。

例如:

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  
 }}

Once you are using variable arguments you have to consider on below points.

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

例如:

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