简体   繁体   中英

How realy work Varargs in java?

I am now learning Varargs in java. I wrote this method:

 public static void vrati(Object... arguments){
    for(Object i : arguments)

    System.out.println(i);
}

Then I called the method:

 main.vrati(8,2,"String");

So my question is: does varargs cast primitive types to object? Because I have mixed in int and String in this method call and can access them like is one object.

So my question does varargs cast primitive types to object?

It casts to the type of the array. If you have

a(int... ints)

They will be int

and if you have

b(double... doubles)

they will be doubles even if you write b (1, 2.0f, 10L)

If you have an

c(Object... obj)

it will autobox primitives. This is not a feature of var-args but how types are autoboxed as needed anyway.

Varargs are the variable number of arguments. It allows arguments from 0 to unlimited. Varargs are denoted by ... (triple dots). Varargs must be the last argument of the function. Consider the following program :

class Test
{
    static void display(Object ... o)
    {   
        for(Object o1 : o)
            System.out.print(o1+" ");
        System.out.println();
    }
    public static void main(String []args)
    {
        display();
        display(10,20,30,40,50);
        display(10.2f,20.3f,3.14f);
    }
}

"Varargs" are mainly syntactic sugar.

So

Whatever...

turns into

Whatever[]

In other words: the method takes an array of the Vararg-type you are using.

And the compiler makes sure that each and any invocation of a vararg-method receives an array (so the compiler is inserting the new Whatever[] more or less for you).

And please note: the fact that your example relies on auto-boxing has nothing to do with the fact that you are also using varargs.

If the signature of your method would have been Object[] instead, it works the same way (minus the little thingy that you have to pass an array now, instead of just listing your values, separated by comma).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM