Java variable parameters

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

Java1.5 adds new features: variable parameters: applicable to the number of parameters uncertainty, to determine the types of Java, the variable parameters for array processing. note: variable parameters must be located in the last. When the variable parameters of a Shuduoyuyi time, will have a not last, so only support a variable parameter. Because the number of parameters is not fixed, so when there is the same type parameters, Java cannot distinguish incoming parameters are variable parameters before or behind a parameter, so the only variable parameter is the last item.


public class VariableParameter {

    public static void main(String[] args) {
        
        //The use of variable parameters
        System.out.println(add(2,3));
        System.out.println(add(2,3,4));
        
        //The use of array
        int[] x1=new int[]{2,3};
        int[] x2=new int[]{2,3,4};
        System.out.println(add2(x1));
        System.out.println(add2(x2));
    }
    
    /*
     *1 can only appear at the end of the parameter list,  
     *2... In the variable type and variable name., 
     *Methods 3 call variable parameter, the compiler creates a array implied for the variable parameters in the method body, a form of array access the variable parameters. 
     *Type 4 parameters must be consistent
    */
    public static int add(int x,int ... args){
        int sum=x;
        for(int i=0;i<args.length;i++){
            sum+=args[i];
        }
        return sum;
    }
    //Afferent array parameter
    public static int add2(int[] args){
        int sum=0;
        for(int i=0;i<args.length;i++){
            sum+=args[i];
        }
        return sum;
        
    }
}


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Demi at November 12, 2013 - 9:17 PM