How to call a varargs method with an additional argument from a varargs method

心已入冬 提交于 2019-12-01 15:46:45

Now I see only one way: create array with dimension [args] + 1 and copy all items to new array.

There is no simpler way. You need to create a new array and include myobj as last element of the array.

String[] args2 = Arrays.copyOf(args, args.length + 1);
args2[args2.length-1] = myobj;
sys(args2);

If you happen to depend on Apache Commons Lang you can do

sys(ArrayUtils.add(args, myobj));

or Guava

sys(ObjectArrays.concat(args, myobj));

You may call sys() twice if the order doesn't care:

T myobj=new T();
sys(myobj);
sys(args);

If you can't use this, switch to collections (eg. LinkedList) for all of your functions.

If you can use Guava, then you can do:

sys(ObjectArrays.concat(myobj, args))

Java 8 solution:

sys(Stream.concat(Arrays.stream(args), Stream.of(myobj)).toArray(T[]::new));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!