GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes convert array to Arraylist Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "convert array to Arraylist" Watch "convert array to Arraylist" New topic
Author

convert array to Arraylist

Raj Ohadi
Ranch Hand

Joined: Jun 30, 2006
Posts: 316
If I have an array of a class like

Student[] students = initializeStudentArray();

how do I convert this "student" array into a list and make sure the objects in the list are all of type "Student"
I know Arrays.asLIst() is useful. But it does not seem to ensure the objects in the list created is the same type as "Student". What's the easy API to convert Student[] into a list and each element in the list is "Student" object.

Don't tell me to loop through the "students" array and create a new list from there..

Similar question for "converting a list whose element type is "Student" to an array whose elements are "Student" type. what API can be used to do that ?

Thanks.
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3016
    
  10
Raj Ohadi wrote:I know Arrays.asLIst() is useful. But it does not seem to ensure the objects in the list created is the same type as "Student".

Mmm, really? I think it does. What makes you think it doesn't? Have you tried it?

The only exception I can think of is that it can also contain nulls. If that's a problem, I don't know of any standard library method that will help you. But it's easy to loop through the "students" array and create a new list from there, excluding any nulls you find (or throwing an error).

Raj Ohadi wrote:Don't tell me to loop through the "students" array and create a new list from there..

How sad. I guess you won't be able to solve this, even though the solution is very, very simple. Too bad.

You may also want to look at Collections.checkedList(). But really, Arrays.asList() already solved most of your problems, and it's unclear what else you need.

Raj Ohadi wrote:Similar question for "converting a list whose element type is "Student" to an array whose elements are "Student" type. what API can be used to do that ?

Have you looked carefully at the API for List?
 
GeeCON Prague 2014
 
subject: convert array to Arraylist