aspose file tools*
The moose likes Beginning Java and the fly likes System.arraycopy() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "System.arraycopy()" Watch "System.arraycopy()" New topic
Author

System.arraycopy()

Anthony Smith
Ranch Hand

Joined: Sep 10, 2001
Posts: 285
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

Joined: Mar 16, 2001
Posts: 986

What is not working about it?
And don't you want to say "tmparr.length" instead of "list.size()"?


Please ignore post, I have no idea what I am talking about.
Anthony Smith
Ranch Hand

Joined: Sep 10, 2001
Posts: 285
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

Joined: Jan 30, 2000
Posts: 18671
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.


"I'm not back." - Bill Harding, Twister
Ron Newman
Ranch Hand

Joined: Jun 06, 2002
Posts: 1056
What error are you getting when you try to use arraycopy?


Ron Newman - SCJP 1.2 (100%, 7 August 2002)
 
 
subject: System.arraycopy()