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.