Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

java - Why varargs should be the last in method signature?

If I try to write a method like below

public void someStuff(Object ... args, String a )

I get this error

The variable argument type Object of the method someStuff must be the last parameter.

I don't fully understand the requirement of variable argument type to be the last. Any inputs will be helpful.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The variable argument has to be the last so the compiler can work out which argument is which.

For example, say you pass

"test", "test", "test", "test"

into your function

public void someStuff(Object ... args, String a)

Java cannot work out if you want the args variable to contain 3 or 4 strings. It may be obvious to you at the time of writing but it's ambiguous.

However, when it's the other way around

public void someStuff(String a, Object ... args)

The Java compiler sees the first string, stick it into "a" and then knows that the remaining strings can be safely put into args and there is no ambiguity over the variables.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...