Evo. G Tech Team Forum
Welcome to Evo. G Tech Team Forum. We have moved to a new website : www.evogtechteam.com

Thanks you.

by Evo. G Tech Team Management.

C3 (cont) Coping Arrays

View previous topic View next topic Go down

C3 (cont) Coping Arrays

Post by LifeStyle on September 1st 2014, 23:06

SUBTOPIC: COPYING ARRAYS
• There are THREE methods to duplicate an array or part of an array which are using:
1) for loop
2) = operator
3) arraycopy() method
Method 1: for loop
• Copy individual element based on the condition.
• Example:
int x [] = {1, 12, 23};
int y [] = new int [5];
for(int i=0; iy[i] = x[i];
//to print
for(int j=0;jSystem.out.print(" "+y[j]); //the output is: 1 12 23 0 0
Method 2: = operator
• Copy ALL elements from one array to another array(s).
• Disadvantage: It is copy by reference as x[] and y[] share same memory location. (If element has
been changed at x[], it will also change the element at y[] and vice versa)
• Example:
int x [] = {1, 12, 23};
int y [] = new int [3];
y = x; //copy x to y
//modify y
y[1]= 42;
//print x
for(int j=0;jSystem.out.print(“ “+x[j]); //the output is: 1 42 23
Method 3: arraycopy() method
• Syntax:
System.arraycopy (sourceArray, sourcePosition,targetArray,targetPosition,
length);
• Example:
Study the situation below:
int [] x = {7, 8, 9};
x 7 8 9
0 1 2
Array int x has three elements: 7, 8 and 9.
There is another array named y. The size of array y is also three.
int [] y = new int[3];
Let’s say, we need to copy element 8 and 9 to array y. So that the array y will have elements like this:
y 8 9 0
0 1 2
The method to copy some elements from x to y:
System.arraycopy (x, 1, y, 0, 2);
Element 8 is at index 1 The target index is 0
at array y
Only two elements are
copied from array x
avatar
LifeStyle
Beginner
Beginner

Posts : 10
Points : 28370
Reputation : 0
Join date : 2014-01-06
Location : Behide you

View user profile

Back to top Go down

View previous topic View next topic Back to top


 
Permissions in this forum:
You cannot reply to topics in this forum