Varargs allows variable number of arguments in methods and constructors. Varargs permette numero variabile di argomenti a metodi e costruttori. Let’s start with a simple example. Si parte con un semplice esempio.

public static void main(String … args) { public static void main (String… args) (
for(String arg:args) { for (String arg: args) (
System.out.println(arg); System.out.println (ARG);
} )
} )

Varargs can be thought of as an array with simplifications. Varargs può essere pensato come una matrice con semplificazioni. A simple use case is: int sum(int… data) Un semplice caso d'uso è il seguente: int somma (int i dati…)

Key Points Punti chiave

  • Method with varargs is called only when no other method signature matches the invocation. Metodo con varargs è chiamato solo quando nessun altro metodo di firma corrisponde l'invocazione.
  • Only one varargs per method can be declared. Un solo metodo per varargs possono essere dichiarati.
  • Varargs should be the last argument(set) for a method. Varargs dovrebbe essere l'ultimo argomento (imposta) per un metodo. So public void varargtest(int i, String … args) is valid but public void varargtest(String … args, int i) is not. Public void così varargtest (int i, String args…) è valido ma non public void varargtest (String… args, int i) non lo è.
  • Zero or more arguments can be passed for varargs unlike an array where at least a null has to be provided. Zero o più argomenti possono essere passati per varargs a differenza di un array in cui almeno uno ha nulla da fornire.

Now you are all set to play with varargs in Java. Ora è stato tutto configurato per giocare con varargs in Java. Go forth and enjoy! Andare avanti e divertiti!