A function for writing variable long parameters in Java __java

Source: Internet
Author: User

More and more Java libraries are using variable-length parameters that are no longer necessary to add a new object[.


So how do you implement one of these variable-length functions yourself?

Let's do this by adding a long string of integers as an example:


variable length parameter is used t ... It is indicated that in the function body, it is actually an array of type T, and then the variable length parameters like an array of operations are done.

Example:

public class Kmath {public
    static int add (int ... args) {int result
        = 0;
        for (int arg:args) {result
            = arg;
        }
        return result;
    }

It should be noted that this t ... You must put it on the last side of the argument list to avoid ambiguity.


Test code:

public class Variablearglengthlisttest {
    @Test public
    void Test_variable_length_arg_list_works () {
        Assertthat (Kmath.add (1, 2, 3, 4), is ());
        Assertthat (Kmath.add (1, 2, 3), is (6));
        Assertthat (Kmath.add (1, 2), is (3));
        Assertthat (Kmath.add (1), is (1));
    }

Done.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.