-1

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...

dyy.alex
  • 514
  • 2
  • 4
  • 16
  • A `List` is an `Object`. You are passing an `Object[]` with one element, the `List`. – Andy Turner Aug 18 '20 at 14:34
  • 1
    Does this answer your question ? [How to pass an ArrayList to a varargs method parameter?](https://stackoverflow.com/questions/9863742/how-to-pass-an-arraylist-to-a-varargs-method-parameter) – Eklavya Aug 18 '20 at 14:38
  • Yep, you are right, i am using toArray() now. Thanks – dyy.alex Aug 18 '20 at 14:41

2 Answers2

2

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()));
mahdilamb
  • 535
  • 3
  • 11
0
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.

Saurabh Jhunjhunwala
  • 2,832
  • 3
  • 29
  • 57