| Author |
wrt to java Array programming
|
RaviNada Kiran
Ranch Hand
Joined: Jan 30, 2009
Posts: 528
|
|
I had always difficulties with Arrays .
int a[] = {1,2,3,4,5,6,7,8};
How can i copy the above array a[] data into a new array b[]
int b[] = new int[a.length];
Please help waiting for your responses
|
If you want something you never had do something which you had never done
|
 |
Balu Sadhasivam
Ranch Hand
Joined: Jan 01, 2009
Posts: 874
|
|
Wont the for loop works well ? just iterate the length of array and grab each index values and assign it to new array
|
 |
John de Michele
Rancher
Joined: Mar 09, 2009
Posts: 600
|
|
This will work, too:
John.
|
 |
Balu Sadhasivam
Ranch Hand
Joined: Jan 01, 2009
Posts: 874
|
|
John de Michele wrote:This will work, too:
John.
Arrays.copyOf is available from Java 6.0.
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16815
|
|
Another option is to use the arraycopy() method of the java.lang.System class.
Henry
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32833
|
|
|
Another option is to use the clone() method of the array. It will work nicely for a plain simple 1-subscript array like that.By the way: write int[] a rather than int a[]. That asserts that the type of a is int[] not int.
|
 |
RaviNada Kiran
Ranch Hand
Joined: Jan 30, 2009
Posts: 528
|
|
Thanks for your time , But i dont want to do it any operation with the help of java.util.Arrays.
|
 |
RaviNada Kiran
Ranch Hand
Joined: Jan 30, 2009
Posts: 528
|
|
int a[] = {1,2,3};
int b[] = new int[a.length];
for(int i=0;i<a.length;i++)
{
a[i]= b[i];
}
System.out.println(b[2]);
i am getting 0 , can anybody please tell me whats the correct approach to copy data from one array to another??
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16815
|
|
i am getting 0 , can anybody please tell me whats the correct approach to copy data from one array to another??
Generally, when copying a source to a target, it is a good idea to put the target on the left side of the assignment.
Henry
|
 |
RaviNada Kiran
Ranch Hand
Joined: Jan 30, 2009
Posts: 528
|
|
|
Thanks a lot Henry the code is working fine.
|
 |
 |
|
|
subject: wrt to java Array programming
|
|
|