Why varargs should be the last in method signature?

前端 未结 5 1892
礼貌的吻别
礼貌的吻别 2020-12-03 01:45

If I try to write a method like below

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

I get this error

The variabl

5条回答
  •  情歌与酒
    2020-12-03 02:02

    Well a String is also an instance of Object so if you are using varargs your vararg array has to be the last parameter because the compiler can't really decide what is args and what is your string a. Think of the method call as a tuple of method name and a list of objects which are your parameters. If you have two methods like so:

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

    The compiler couldn't decide what method to choose for someStuff("Hello", "Hello") . If you put your String a as the first argument it can decide that someStuff(String, String) is more specific than someStuff(String, Object).

提交回复
热议问题