在方法中的参数,Object… 与 Object[],这两者功能相同吗?

huangapple go评论65阅读模式
英文:

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, &quot;field&quot;, &quot;baz&quot;, &quot;fox&quot;));

Now, I want to use it like this one:

List&lt;String&gt; list = new ArrayList(3);
list.add(&quot;field&quot;);
list.add(&quot;baz&quot;);
list.add(&quot;fox&quot;);
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&lt;String&gt; list = new ArrayList(3);
list.add(&quot;field&quot;);
list.add(&quot;baz&quot;);
list.add(&quot;fox&quot;);
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.

huangapple
  • 本文由 发表于 2020年8月18日 22:22:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/63470692.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定