j2se5.0 instance---variable length parameters

Source: Internet
Author: User
J2SE variable length parameter (Varargs)
As with generics, variable-length parameters are a language feature in C + + that is not in Java, and in the past if we wanted to pass a variable number of functions to a function, we had to first put the arguments into an array and pass the array to the function. Just like the following:

object[] arguments = {640, "KB", "Anybody", "Bill Gates"};

String result = Messageformat.format (

' {3}:{0,number,integer}{1} ought to is enough for {2} '

arguments);

In j2se5.0, the parameters are still placed in an array to the corresponding method, but the difference is that you no longer need to manually create the array, but only to list those parameters, the other work by the virtual machine for you to do. So now we can write this:

String result = Messageformat.format (

' {3}:{0,number,integer}{1} ought to is enough for {2} '

640, "KB", "Anybody", "Bill Gates");

We use a sample function to illustrate the definition of using variable-length parameter functions. This function prints out the names of a few dogs that a person raises.

private void Printdognames (String ... dogs)

{

System.out.println ("I have" + Dogs.length + "dogs:");

for (String dogname:dogs)

{

System.out.println (Dogname);

}

}

In fact, the variable length parameter dogs is an array.

There can be only one variable length parameter in a function, so a definition similar to the following is not legal:

private void Printdognames (String ... dogs,float ... dogage)

If you decide to set the function argument to a variable length, you have to think of a situation where the calling program will probably not give you any arguments, this time as an array of arguments of length 0, which is completely syntactically valid, so you have to take this into account in the definition of the function.


Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.