• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

System.arraycopy()

 
Anthony Smith
Ranch Hand
Posts: 285
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got a javabean that takes a ResultSet from a db and stores the values from that row into one of my objects (User). I take each one of those objects and add them to an arraylist.
I then create a temp array of type User with the size of the ArrayList and create a Object array setting the value to the arrayList usign the toArray function. Then I do a 'deep copy'.
for (int i=0; i<tmparr.length; i++) { tmparr[i] = (User)arr[i]; }
Then I saw the System.arraycopy so I figured I could do a:
System.arraycopy(arr,0,tmparr,0,list.size());
but I can't SO cannot I not use arraycopy? or is my best bet to continue like I have it now, with the for loop.
 
William Barnes
Ranch Hand
Posts: 986
Eclipse IDE Firefox Browser Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is not working about it?
And don't you want to say "tmparr.length" instead of "list.size()"?
 
Anthony Smith
Ranch Hand
Posts: 285
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Problem is that I cant use arraycopy. the other way works fine, but I wanted to double check to make sure that I coudl not use arraycopy.
When I do list.toArray() that return value is an Object. SO now it is an Object array. I cant do a cast on it. and it seems that arraycopy must use the same array types in order to work.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you've got a List containing User objects and you want to make a User[] array from it, try this:

By using an existing array of the appropriate type, you can force toArray() to do the work for you, rather than creating an Object[] which you then must cast again.
However, this does not explain your problem with arraycopy(). What exactly happens when you try to use it? Are you sure that your List really has User object in it, or might it have other objects as well (or instead)? If they =aren't really User objects, the new approach won't work either, and you'll get a ClassCastException explaining the problem. Please let us know what the error message actually says, and then sho how you created and loaded the List in the first place.
 
Ron Newman
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What error are you getting when you try to use arraycopy?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic