简体   繁体   English

如何将对象类型列表转换为对象数组

[英]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 可以使用以下方法完成从List到数组的来回切换,反之亦然

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 有关更多信息,请参见这些方法的javadoc( List#toArrayArrays#asList )。

使用列表的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) 顺便说一下,您在代码中两次使用了users (作为数组和列表)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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