Sometimes, the number of parameters we pass into the method is not fixed, in order to solve this problem, we generally use the following method:
1. Overloading, overloading several methods, as much as possible to satisfy the number of parameters. Obviously that's not a good idea.
2. The parameter is passed in as an array. Although we can do this in a single way, however, in order to pass this array, we need to declare an array first and then add the parameters one by one to the array.
Now, we can solve this problem with variable length parameters.
Declare variable-length parameters as follows:
public void MyMethod (String arg1,object ... args)
The use of ... Declares a parameter as a variable-length parameter.
Obviously, the variable length parameter must be the last parameter.
Please see below the Tang monk teacher to Goku to speak the Sutra example:
Package com.kuaff.jdk5;
public class VARARGS1
{
public void Speak (String name,object ... arguments)
{
for (Object object:arguments)
{
System.out.println (object);
}
}
public static void Main (string[] args)
{
Varargs1 va = new Varargs1 ();
Va.speak ("Wukong", "Man and Goblin are mother born,");
Va.speak ("Wukong", "different people are the people who are born,", "Demon is the demon of the mother Born,");
}
}
The arguments in speak are declared as variable-length arguments, so you can pass multiple arguments to the Speak method.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.