Reputation: 1179
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
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
Reputation: 36601
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
Upvotes: 4
Reputation: 62145
Use List's toArray
method:
return users.toArray(new User[users.size]);
Upvotes: 3