enterprize
enterprize

Reputation: 1179

How to convert a List of Object type to an array of objects

I have to return array of objects from a method. The objects are initially held in a List of objects type. I am having difficulties in assigning values from list of objects to array of objects. How do I do that. Here is my code:

public User[] getUser() {

    User[] users = null;

    Session session = HibernateUtil.getSessionFactory().openSession();
    List<User> users = session.createQuery("from User").list();
    for (Iterator<User> iter = users.iterator(); iter.hasNext(); ) {
        User user = iter.next();
        //Here I need to assign User type object from list to array of objects
    }
    return users; // returning nothing so far
}

Upvotes: 1

Views: 195

Answers (3)

Timo Willemsen
Timo Willemsen

Reputation: 8857

Would this solve your problem?

usersList = users.toArray(new User[users.size()]);

By the way you're using users twice in your code (as array and as list)

Upvotes: 1

Robin
Robin

Reputation: 36601

Switching back and forth from Lists to arrays and vice versa can be done with the methods

User[] array = users.toArray( new User[usersList.size()] );//from list to array
List<User> usersList = Arrays.asList( userArray );//from array to list

See the javadoc ( List#toArray and Arrays#asList ) of those methods for more information

Upvotes: 4

helpermethod
helpermethod

Reputation: 62145

Use List's toArray method:

return users.toArray(new User[users.size]);

Upvotes: 3

Related Questions