0

If someone could explain what E... means in this addMany method it would be very appreciated. Example code:

    /**
     * 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;
    }
KrakenJaws
  • 155
  • 12

1 Answers1

1

This is called variable arguments. It allows the method to accept zero or multiple arguments.If we have no idea about the count of the arguments then we have to pass this in the method.As an advantage of the variable arguments we don't have to provide overloaded methods so less code.

Ex:

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.

  • There can be only one variable argument in the method.
  • Variable argument must be the last argument.

Ex:

void method(Object... o, int... i){}//Compile  error
void method(int... i, String s){}//Compile  error  
Madushan Perera
  • 2,568
  • 2
  • 17
  • 36