Java: a method for writing multiple parameters

Source: Internet
Author: User

Write JavaProgramWhen multiple parameters are required for a method. For example, a summation method:

Public int add (INT [] list ){
Int sum = 0;
For (INT I = 0; I <list. length; I ++)
Sum + = list [I];
Return sum;
}

Of course, you can also use the overload method:

Public int add (int A, int B ){
Return A + B;
}

Public int add (int A, int B, int c ){
Return A + B + C;
}

If the program is less likely, the reload method may be a good choice. If there are many possible cases, the above method will undoubtedly be more scalable

Strong. But is there any better way?

JDK 5 optimizes the for loop and can be used to write more conciseCode:

Public int add (Int... list ){
Int sum = 0;
For (INT item: List)
Sum + = item;
Return sum;
}

Note that add (Int... list) is represented by a variable number of parameters, which is unknown to many Java learners.

In addition, variable parameters must be placed at the end of all parameters, such

Add (Int... list, int)Yes,Add (int A, Int... List)Is correct.

 

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.