Forums Register Login

Arrays.copyOfRange() and System.arraycopy

+Pie Number of slices to send: Send
Hi,

When to use below two functions. Are there special cases in which one is preferred to use over other?

Arrays.copyOfRange() and System.arraycopy


I was looking here

http://www.programcreek.com/2015/03/system-arraycopy-vs-arrays-copyof-in-java/

int[] copied = Arrays.copyOf(arr, 10); //10 the the length of the new array
System.out.println(Arrays.toString(copied));




copied = Arrays.copyOf(arr, 3); // are they truncating new array copied size from 10 to 3 in this step???
System.out.println(Arrays.toString(copied));



The difference is that Arrays.copyOf does not only copy elements, it also creates a new array. System.arrayCopy copies into an existing array.



i was not clear on above point based on the example in the link?

please advise.
+Pie Number of slices to send: Send
I think you need to read the documentation for the two methods: Arrays#copyOf and System#arraycopy. As you said, the difference is that for arraycopy, you have to provide a destination array.Since arrays do not override toString you can see the hashCode for the different arrays when you print them out. It will read something like I]@ab12cd34. You should get the same hashCode for the two calls to print destination.
+Pie Number of slices to send: Send
Welcome to the Ranch
Can you shoot lasers out of your eyes? Don't look at this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 1515 times.
Similar Threads
Array, reading input method..
Regarding array
How to add elements to the left side of an array?
Skip the last string on a comma-delimited line
Magic Square, array/recursion
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 14:05:02.