Variable number of parameters and autoboxing

There are two types in Java, the primitive type and the compound type (or the objects).

233.getClass();                // NOOOOOOOOOO!
new Integer(233).getClass();   // GOOD :)

In the first line of the code block above, the compiler will not automatically wrap 233 as an Integer object and we have to do it manually as the second line shows.

At other times, the compiler will do the autoboxing for us (since JDK 5.0). We will see autoboxing in the following example of variable parameters.

public class JavaApplication {
    public static void typeDetect(Object ...args) {
        System.out.println(args.length + " arguments in total.");
        for(Object obj : args) {
            System.out.println(obj.getClass());
        }
    }
    public static void main(String [] args) {
        typeDetect(1, "one", '1', 2.33);
    }
}

Output

4 arguments in total.
class java.lang.Integer
class java.lang.String
class java.lang.Character
class java.lang.Double

So as you see, it is easy to deal with variable number of parameters. All the parameters are collected in the array args. This is possible because all classes in Java are subclasses of Object and the compiler will do the autoboxing job for the primitive types just as the output suggests.

The python counterpart is like this:

def func(a, b, c, *rest):
    pass







你可能感兴趣的:(java,variable,number,Parameters,AutoBoxing,of)