krzakov
krzakov

Reputation: 4111

Spreading array of objects to the list of arguments

I want to spread my array of Objects like this:

int size  = 3;   /* sample size */
Object[] arrayOfObjects = new Object[size];
/* initialize this array by Objects */

and by using some magical method, get this on output:

Object obj1, Object obj2, Object obj3

I need this kind of output, because I need to use method which allows list of arguments.

PS. My API provides addAll method, type of argument is: Iterable <Some_Type> which I don't really understand.

Upvotes: 0

Views: 2710

Answers (2)

Jay Smith
Jay Smith

Reputation: 481

addAll is a method that "iterates" over the collection and adds all elements to another datastructure.

Iterable, for you this would be Iterable, creates a datastructure called an iterator that allows you to iterate over the datastructure yourself.

Object[] arrayOfObjects = new Object[size];
Collection<Object> myNewCollection = new ArrayList<Object>();
// use the addAll
myNewCollection.addAll(arrayOfObjects);

// use an iterator
Iterator<Object> iter = myNewCollection.iterator();
while(iter.hasNext()){
    Object object = iter.next();
    // do something with the object
}

Upvotes: 0

jlordo
jlordo

Reputation: 37823

Use

yourDataStructure.addAll(Arrays.asList(arrayOfObjects));

this makes use of the addAll() method with a Iterable<Some_Type> you mentioned in your question.

Upvotes: 1

Related Questions