71

Need to figure out what is the difference between ... and arrays in JAVA, also an array list.

It seems we can use both as unlimited, but ... is rarely used.

Really appreciate any help you can.

0

3 Answers 3

142

The three dots can only be used in a method argument, and are called 'varargs'. It means you can pass in an array of parameters without explicitly creating the array.

private void method(String[] args) {} is called like method(new String[]{"first", "second"});

private void method(String... args) {} is called like method("first", "second");

1
  • 32
    It's worth noting that the varargs are just sugar. The method actually takes an array, plain array. method(String... args) can be invoked as method("first", "second"), but it can just as well be invoked as method(new String[]{"first", "second"}).
    – yshavit
    Jul 25, 2012 at 0:08
18
  • An array is a fixed length collection of objects. e.g. new int[5];
  • An ArrayList is a variable length collection of objects. e.g. new ArrayList<Integer>();
  • The ... in variadic functions is a part of a method signature denoting an array of parameters. e.g. public void printLines(String... lines)
1

In other words, method(String...) means passing a variable number of parameters to the method.

1
  • Or passing no parameter in case of a method with one parameter (Varargs) because they're optional. It's up to the developer to properly implement the method to handle having zero or more of them.
    – S_intg
    Mar 11, 2020 at 11:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.