将元素添加到 Java vararg 调用的最易读的方法
如果我有一个方法 public void foo(Object... x)
,我可以用这种方式调用它:
Object[] bar = ...;
foo(bar);
但是,这不起作用:
Object baz = ...;
Object[] bar = ...;
foo(baz, bar);
显然,它可以通过创建一个数组来完成size 1 大于 bar
并复制 baz
和 bar
的内容。但有没有更易读的快捷方式呢?
If I have a method public void foo(Object... x)
, I can call it in this way:
Object[] bar = ...;
foo(bar);
However, this doesn't work:
Object baz = ...;
Object[] bar = ...;
foo(baz, bar);
Obviously, it can be done by creating an array with size 1 greater than bar
and copying baz
and the contents of bar
there. But is there some more readable shortcut?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Guava 的
ObjectArray
类提供了将单个对象连接到数组的开头或结尾的方法,主要是为了这个目的。没有办法避免线性开销,但它已经为您构建和测试。Guava's
ObjectArrays
class provides methods to concatenate a single object to the beginning or end of an array, largely for this purpose. There's no way to get around the linear overhead, but it's already built and tested for you.不幸的是,没有现成的方法可以使其更具可读性。
但是,您可以创建一个辅助方法,该方法接受一个数组和一个 vargs 参数,并返回附加了 varargs 的数组。
像这样的东西:
Unfortunately, there's not out-of-the-box way to make that more readable.
However, you could create a helper method that would take an array and a vargs parameter and returns the array with the varargs appended.
Something like this:
一种可能是重载
foo()
:A possibility would be to overload
foo()
: