It's not a secret anymore!
The moose likes Beginning Java and the fly likes Copying array issue Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Copying array issue" Watch "Copying array issue" New topic

Copying array issue

Rob Hunter
Ranch Hand

Joined: Apr 09, 2002
Posts: 832
The below snippet of code throws a nullPointerException but if I replace with the following snippet of code it "works" but the array points to the array passed in and that's no good because the array coming in needs to change on each call. How can I effectively copy the array into the instance array lineCoords?

Matthew Brown

Joined: Apr 06, 2010
Posts: 4544

If you look at the documentation for arraycopy, you'll see that you can't pass a null value in for the array. You've got to create the array first (at the size you want). If you think about it, that has to be the case as you're passing the reference by value. If you pass null in, it can't possibly result in lineCoords pointing at a new object.

However, I suggest you check Arrays.copyOf instead, as that will create the array for you.
jishnu dasgupta
Ranch Hand

Joined: Mar 11, 2011
Posts: 103

If you are sure about the size of the array you want to pass, you could just make aan array of that size, make lineCoords, point to it, and then copy the elements of coords to it. Although its is a bit cumbersome, I beleive their must be easier methods...

If debugging is the process of removing bugs, then programming must be the process of putting them in. -- Edsger Dijkstra

Hunter McMillen
Ranch Hand

Joined: Mar 13, 2009
Posts: 492

No need to do the copying yourself when methods already exist to do so, Matthew's suggestion is a good idea.


"If the facts don't fit the theory, get new facts" --Albert Einstein
I agree. Here's the link:
subject: Copying array issue
It's not a secret anymore!