简体   繁体   中英

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
}

Switching back and forth from List s 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

使用列表的toArray方法:

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM