Pit father of Java variable parameters, to have my whole sad case. .

Recently wrote a feature point, with the variable parameters in Java, really made me sad case. .

What is a variable parameter?

The method parameters is Object... argsthree points form a plurality of parameters may be received parameters.

The actual code is not a quote, look at it this example:

Example 1

public static void main(String[] args) {
    test("name=%s&memo=%s", "Java技术栈", "666");
}

private static void test(String text, Object... params) {
    String result = String.format(text, params);
    System.out.println(result);
}

Guess what the result is? The results we imagine:

name=Java技术栈&memo=666

Example 2

public static void main(String[] args) {
    test("name=%s&memo=%s", "Java技术栈");
}

private static void test(String text, Object... params) {
    String result = String.format(text, params, "666");
    System.out.println(result);
}

I put "666" moved to the inside of the sub-way into the final format, and then look at what the results are.

name=[Ljava.lang.Object;@4cb2c100&memo=666

This is not the result I wanted, the variable parameter array params object address as the output value came out, made me sad case, I finally get rid of the variable parameters. .

JDK there are many useful to variable parameters, the actual development can not recommend the use of a variable reference, it brings problems and potential problems will be far greater than the convenience, such as reconstruction method, updating, or other will bring to a lot of problems.

About variable parameters, there is also the development of standardized, you can not just write. I found Ali Baba "Java Development Manual" Statute on variable parameters.

Type the same parameters, same business meaning, can use Java variable parameters, avoid the use of Object.

Description: Variable parameters must be placed at the end of the argument list. (Do not try to promote the students variable parameter programming)

正例: public List<User> listUsers(String type, Long... ids) {...}

The acquisition of Alibaba latest Java development manual in PDF format, we can focus on Java technology stack micro-channel public number, in the background reply: manual, you can obtain.

Alibaba is also not recommended for everyone to cooperate variable parameters, we can see that it brings there will be more pit pit. .

In addition, the stack has compiled a large number of long series of core Java technology knowledge articles focus on Java technology stack micro-channel public number, reply in the background Keywords: java, you can get the latest version.

This article first appeared in the original micro-channel public number: Java technology stack (id: javastack), reproduced Please keep this information intact.

Reproduced in: https: //my.oschina.net/javaroad/blog/3060053

Guess you like

Origin blog.csdn.net/weixin_33827965/article/details/91949050