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.

Join the forum, it's quick and easy

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.
Evo. G Tech Team Forum
Would you like to react to this message? Create an account in a few clicks or log in to continue.

C3 (cont) Coping Arrays

Go down

C3 (cont) Coping Arrays Empty C3 (cont) Coping Arrays

Post by LifeStyle 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
LifeStyle
LifeStyle
Beginner
Beginner

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

Back to top Go down

Back to top

- Similar topics

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