• Post Reply Bookmark Topic Watch Topic
  • New Topic

Arrays.copyOfRange() and System.arraycopy  RSS feed

 
sai rama krishna
Ranch Hand
Posts: 536
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Campbell Ritchie
Marshal
Posts: 56541
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Campbell Ritchie
Marshal
Posts: 56541
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!