Java varargs method param list vs. array

前端 未结 6 1049
迷失自我
迷失自我 2020-12-01 01:50

Varargs:

public static void foo(String... string_array) { ... }

versus

Single array param:

public static void bar(         


        
6条回答
  •  被撕碎了的回忆
    2020-12-01 02:38

    Another difference is efficiency. Objects that are inside an explicit array won't get invoked. However the parameters of a variable argument list are evaluated when the method is pushed on the stack.

    This is apparent when a function call is passed as a parameter that returns the type that is used in the variable argument list.

    Example: someMethod( Object... x) anotherMethod( Object [] );

    someMethod( a(), b(), c()); // a, b and c will be invoked before you get into the method.

    anotherMethod ( new Object[]{a(), b(), c()}); // The methods aren't invoked until the objects are accessed.

提交回复
热议问题