73

The Spring framework uses methods where you can pass as many arguments as you like.

I would like to write a function that can also take an unlimited amount of data. How is this feature called so that I can read about it? Or how can I define it?

Suciu Andrei
  • 131
  • 4
Franz Kafka
  • 10,623
  • 20
  • 93
  • 149

2 Answers2

171

It's called varargs.

It allows a method to take any number of arguments. They are accessible as an array in the method:

public void foo(String... args) {
    for (String arg : args) {
      // do smth with arg.
     }
}

This is syntactic sugar. The compiler hides the array creation, so instead of

 bar.foo(new String[] {"1", "2", "3"});

you write

 bar.foo("1", "2", "3");
Community
  • 1
  • 1
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • Your first link is no longer working. Current link is https://docs.oracle.com/javase/8/docs/technotes/guides/language/varargs.html – Przemysław Głębocki Oct 27 '19 at 18:54
  • private List products = new ArrayList<>(); public void addProduct(Product... args){ products.add(args); } This gives an error "List cannot be applied" I want the method to take an unlimited amount of arguments I.E cart.addProduct(toothbrush, shampoo...) – Ali Hassan Aug 10 '21 at 12:07
16

To add the Bozho's answer, you can also have other arguments in your method before varargs:

// foo(13, "foo", "bar", "baz");
// will print:
// 13 - |foo||bar||baz|
public void foo(int a, String... b) {
    System.out.println(a + " - ");

    for (String c : b) {
        System.out.print("|" + c + "|");
    }
}

However you can not have arguments of a different type after. These do not work:

public void bar(String... b, int b);
public void foo(int a, String... b, int b);
nicovank
  • 3,157
  • 1
  • 21
  • 42