Java Variable Length Parameter vs. Array, Simply Syntactic Sugar?

前端 未结 2 1955
天命终不由人
天命终不由人 2021-01-18 11:33

I am taking a Data Structures and Algorithms course for fun at a local community college. The course\'s textbook is Y. Daniel Liang\'s Introduction to Java Programming,

相关标签:
2条回答
  • 2021-01-18 12:07

    In Java, varargs are a syntactical sugar for creating an array when calling a method. For example, these two calls are equivalent:

    void foo(String... args) { ... }
    
    foo("hello", null, "world", xyz);  // Java 1.5+
    foo(new String[]{"hello", null, "world", xyz});  // All versions of Java
    

    Varargs doesn't make anything new possible (by definition of syntactic sugar), but it reduces verboseness and makes some constructs much more agreeable to implement. For example, some of my favorite uses of vararg include: PrintStream.printf(), String.format(), Method.invoke().

    Other good applications of varargs:

    // This one is in the Java standard library
    Collections: void addAll(Collection<? super T> c, T... elements);
    
    // Custom examples
    int max(int... nums);
    void doOperation(File x, String y, SomeEnum options...);
    

    Additionally, Java's varargs bring the language up to parity with the vararg support in C, Python, JavaScript, and other languages. So if a frequently recurring design (such as max()) works best with varargs, Java is no longer the odd language that requires an uglier implementation.

    0 讨论(0)
  • 2021-01-18 12:29

    The '...' parameters you are talking about are called varargs.

    Some differences to note:

    • varargs can be passed no parameters (basically ignored), null, or an indeterminate number of arguments, while array parameters must be passed an array or null
    • varargs must be the last parameter of your method, whereas it doesn't matter for array parameters. This is because of this special property of varargs, which is probably the most significant difference between the two things you posted:

    The three periods after the final parameter's type indicate that the final argument may be passed as an array or as a sequence of arguments

    Source

    So for example, this method:

    public void myMethod(String... args) {}
    

    Could be called with either of these:

    String[] myStrings = {"a", "b", "c"};
    myMethod(myStrings);
    myMethod("a", "b", "c");
    

    See this for a good explanation on when varargs should be used.

    0 讨论(0)
提交回复
热议问题