1

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
}
1
  • just do users.ToArray()...oh...wait...no...nevermind Commented Dec 8, 2011 at 22:42

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

Small typo: new User(usersList...) should be new User[](usersList...). I tried to make the edit, but it won't let me make such a small change.
3

Use List's toArray method:

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

Comments

1

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)

1 Comment

Slight performance thing would be to pass in a new User[users.size()] instead. Otherwise, toArray will take your newly-allocated, zero-length array, see that it's not big enough, and allocate a second array of proper length. If you use users.size() to instantiate the User[], that saves an array allocation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.