This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

System.arraycopy

 
mirko74
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In Java you can copy an array into another using the normal assignment operator =
public class ArrayTest {
public static void main (String[] args) {
Object[] ov;
String[] sa = {"Green", "Blue", "Red"};
ov = sa;
System.out.println("Color = "+ov[1]);
}
}
So why and when should I use the System.arraycopy ?
Moreover, why in Java ov = ... is not the same as ov[0]= like in C++?
 
Naveen Sharma
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Mirko
Here What r u doing is using the same object but with diffrent refrence variable ov,sa. Basically this is a wide conversioning.You r storing an String object refrense in an Object type variable. You have not copy the contents. but you r using the contents by two diffrent refrence names
But arrayCopy function basically copies the contents of two objects(array), from source to destination.
In former case you r taking the same object but two refrences pointing to the same object
but later is for two objects.
Hope u can understand Now


 
Angela Lamb
Ranch Hand
Posts: 156
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So why and when should I use the System.arraycopy?

public static void arraycopy(Object�src,
int�src_position,
Object�dst,
int�dst_position,
int�length)


You can see that System.arraycopy has arguments for specifying the position in the array to copy from/to and the length of the copy. Using the normal assignment operator, that would have to be done by looping through the arrays. It is just a matter of writing less code when you only want to copy part of an array.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic