While browsing programcreek, I found some themes that focus on the basics but can’t be ignored. For example: What are Java mutable parameters? Topics like soul torture are well worth exploring in depth.

I used to pay little attention to the foundation, think that it is not so, can use the line. For example, today’s theme, tube it can be changeable, is not a parameter, but also how much knowledge – with this attitude, I have been rampant rivers and lakes for nearly ten years (wry smile). But when readers come to me with some basic questions, I can hardly answer them, feeling that knowledge is scattered or superficial. Fortunately, recently, I began to wake up, began to ignore any details, gradually, a little “knowledge reserve”.

All right, that’s it. Let’s get down to business. What exactly are Java mutable parameters?

Mutable arguments are a feature introduced in Java 1.5 that allows methods to take any number of values of the same type (IS-A) as arguments. It looks like this.

public static void main(String[] args) {

    print("Heavy");

    print("Heavy"."Silent");

    print("Heavy"."Silent"."The king");

    print("Heavy"."Silent"."The king"."二");

}



public static void print(String... strs) {

    for (String s : strs)

        System.out.print(s);

    System.out.println();

}

Copy the code

The static method print() uses mutable arguments, so print(” sink “) can do it, print(” sink “, “silence “) can do it, and even three, four, or more strings can be passed as arguments to print().

Speaking of variable parameters, I remember there is such a stipulation in the Alibaba development manual.

This means that you should avoid using mutable arguments, and if you do use them, they must be at the bottom of the argument list. Since the pits are limited to the end, there can only be one variable argument (easy, easy). If the variable argument is not the last bit, the IDE prompts the corresponding error, as shown in the figure below.

So how do mutable parameters work?

The principle is simple. When we use mutable arguments, we actually create an array of the number of mutable arguments, place the arguments in the array, and pass the array to the called method.

This is the fundamental reason why you can call methods with mutable arguments using arrays as arguments. The code is shown below.

public static void main(String[] args) {

    print(new String[]{"Heavy"});

    print(new String[]{"Heavy"."Silent"});

    print(new String[]{"Heavy"."Silent"."The king"});

    print(new String[]{"Heavy"."Silent"."The king"."二"});

}



public static void print(String... strs) {

    for (String s : strs)

        System.out.print(s);

    System.out.println();

}

Copy the code

Does it make sense to call a method that takes an array of arguments and then behaves like a mutable argument? If you’re interested, try it (it won’t work, SHH).

So when do you use mutable parameters?

Mutable parameters, mutable parameters, as the name implies, can be defined when a method needs to handle any number of objects of the same type. A good example in Java is the Format () method of the String class, as shown below.

System.out.println(String.format("年纪是: %d".18));

System.out.println(String.format("Age: % D Name: % S".18."Silent King II."));

Copy the code

PS: %d to format the integer into a decimal integer, %s to output a string.

If you do not use mutable parameters, the parameters to be formatted must be concatenated using the + operator. That’s where the trouble starts.

In actual project code, the open source package slf4j.jar often uses mutable parameters in its log output (log4j can’t use mutable parameters, which makes logging multiple parameters a pain). It looks like this.

protected Logger logger = LoggerFactory.getLogger(getClass());

logger.debug("Name is {}", mem.getName());

logger.debug("Name is {}, age is {}", mem.getName(), mem.getAge());

Copy the code

If you look at the source code, you can see the mutable arguments used by the debug() method.

public void debug(String format, Object... arguments);

Copy the code

So what are the caveats when you’re using mutable parameters?

Yes, yes. Avoid overloading methods with mutable arguments — it’s easy for the compiler to fall into self-doubt.

public static void main(String[] args) {

    print(null);

}



public static void print(String... strs) {

    for (String a : strs)

        System.out.print(a);

    System.out.println();

}



public static void print(Integer... ints) {

    for (Integer i : ints)

        System.out.print(i);

    System.out.println();

}

Copy the code

At this point, the compiler has no idea which print() method to call. Print (String… STRS) or print (Integer… Ints), stupid can’t tell.

If you really need to override a method with mutable arguments, you must give clear instructions when calling the method, so that the compiler doesn’t have to guess.

public static void main(String[] args) {

    String [] strs = null;

    print(strs);



    Integer [] ints = null;

    print(ints);

}



public static void print(String... strs) {

}



public static void print(Integer... ints) {

}

Copy the code

The above code can be compiled. Because the compiler knows whether the argument is a String or an Integer, the two print() methods need to be nullated internally in order not to throw a NullPointerException at runtime.


Well, readers, that’s all for this article. Can see here are the most excellent programmers, promotion pay is you 👍. If you don’t like it and want to see more, I’ll recommend a few more.

How does Java get the length of arrays and strings? Length or length()?

Why are Java strings immutable?

How does Java substring() work?

How do I check if a Java array contains a value?

Original is not easy, if you feel a little use, please don’t be stingy with your hands like the power; If you want to see the second brother’s updated article for the first time, please scan the qr code below and follow the official account of Silent King ii. See you in the next article!