Why varargs should be the last in method signature?

前端 未结 5 1897
礼貌的吻别
礼貌的吻别 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 01:56

    It follows the C convention. The C convention in turn is based on CPU architectures which pass arguments on the stack. The first non-vararg arguments end up at a fixed offset in the stackframe. If you could put the vararg arguments first, the stack offset of the following arguments would depend on how many vararg parameters you would have passed. This would greatly complicate the amount of code needed to access them.

    In your example, with String a first, it's conceptually at offset 0 independent how the number of vararg arguments that follow. But with String a last, it could be at offset 0, 4, 8, 12 etc - you'd have to calculate args.size * 4 everytime you needed String a.

提交回复
热议问题