Tips for using variable parameters in a Java method

Source: Internet
Author: User

I haven't written logs for a long time. Recently, due to project shortage, I am studying some Java reflection mechanisms. I want to use this mechanism to better improve and encapsulate the project and code. Today, when I am studying reflection, shenyang binzi encountered a problem that there was a variable parameter when encapsulating a method. The following methods and techniques were found through searching the Internet.

When writing a Java program, 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
 
  
Reload method:

public int add(int a,int b){   return a + b;}public int add(int a,int b,int c){   return a + b + c;}

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

public int add(int... list){   int sum = 0;   for (int item:list)    sum += item;   return sum;}

TIPS:

Add (int... list), three points represent a variable number of parameters. I believe this 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.

Reference: http://www.cnblogs.com/yezhenhan/archive/2012/08/08/2628835.html

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.