英文:
Params in method, Object... VS Object[] , are these two have the same function?
问题
我有一个类似下面的方法:
public IndexRequest source(XContentType xContentType, Object... source) {
// 一些处理
}
我知道如何使用它:
new IndexRequest().source(XContentType.JSON, "field", "baz", "fox"));
现在,我想要像下面这样使用它:
List<String> list = new ArrayList(3);
list.add("field");
list.add("baz");
list.add("fox");
new IndexRequest().source(XContentType.JSON, list));
然后,我发现它已经通过了编译器。但我不确定这个函数是否正确可用...
我能不能使用 Object[]
替代 Object...
?
英文:
I have a method like followed:
public IndexRequest source(XContentType xContentType, Object... source) {
// some process
}
And I kown how to use it:
new IndexRequest().source(XContentType.JSON, "field", "baz", "fox"));
Now, I want to use it like this one:
List<String> list = new ArrayList(3);
list.add("field");
list.add("baz");
list.add("fox");
new IndexRequest().source(XContentType.JSON, list));
And then, I find it has passed the Compiler. But I don't know the function is right to be used...
Can I use Object[] instead of Object...
答案1
得分: 2
有列表和数组之间存在差异。最简单的方法是执行以下操作(将列表转换为数组,注意"toArray"方法):
List<String> list = new ArrayList(3);
list.add("field");
list.add("baz");
list.add("fox");
new IndexRequest().source(XContentType.JSON, list.toArray()));
英文:
There is a difference between a list and an array. The simplest way would be to do the following (converting the list to an array note the "toArray" method):
List<String> list = new ArrayList(3);
list.add("field");
list.add("baz");
list.add("fox");
new IndexRequest().source(XContentType.JSON, list.toArray()));
答案2
得分: 0
public IndexRequest source(XContentType xContentType, Object... source)
在上面的代码片段中,`Object... source` 表示一个对象数组,但也肯定会接受单个对象,这是因为在内部,JVM 会将该对象添加到一个数组中。
在类似的情况下,当您将一个列表传递给该方法时,它会将该列表放入一个名为 `source` 的数组中,因此编译器不会抛出错误。
英文:
public IndexRequest source(XContentType xContentType, Object... source)
In the above snippet, Object... source
refers to an Object array, but will surely accept a single object also, this is because internally, JVM will add that object to an array.
On similar lines, when you pass a list to the method, it puts that list into an array named source
, because of which the compiler did not throw an error.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论