8

What I am trying to do here is convert an array to Collection.

How to do this properly?

Here is my array:

PersonList[] personlist = restTemplate.getForObject(url, PersonList[].class);

What I doing there is, I get JSON value and consume with restTemplate, then I put it in PersonList array object, but I want to return the value as Collection. Example:

This is very wrong code that I am trying to present:

Collection<PersonList> personlist2 = personlist

It can't bind the array to collection, cause it's different data type. Can I convert it?

1
  • 8
    Try Arrays.asList(personList) Commented May 19, 2015 at 8:53

3 Answers 3

17

You can do this:

List<PersonList> list = Arrays.asList(personlist);

(Is this PersonList itself a list? If not, then why is the class named PersonList instead of Person?).

Note that the list returned by Arrays.asList(...) is backed by the array. That means that if you change an element in the list, you'll see the change in the array and vice versa.

Also, you won't be able to add anything to the list; if you call add on the list returned by Arrays.asList(...), you'll get an UnsupportedOperationException.

If you don't want this, you can make a copy of the list like this:

List<PersonList> list = new ArrayList<>(Arrays.asList(personlist));
Sign up to request clarification or add additional context in comments.

Comments

3

The easiest way would be to use Arrays.asList:

Collection<PersonList> personlist2 = Arrays.asList(personlist)

Comments

0
 PersonList[] personlist = restTemplate.getForObject(url, PersonList[].class);
 ArrayList<PersonList> personlist2 = Arrays.asList(personlist)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.