How to Move Arrays in Java
Arrays are a vital component of any programming language, and Java is no exception. Many operations are built in to Java's implementation of arrays. You can declare them, set or read values from them, and retrieve their lengths without having to call on any special classes or methods. If you need to move the values of one array into another, however, the process is not so simple. Fortunately, the System class provides a convenient method to accomplish this task.
Things You'll Need
- Text editor
- .java program file
- Array to move values from
- Array to move values to
Instructions
-
-
1
Open the .java file containing the array whose values you wish to move, using your preferred text editor.
-
2
Type "System.arraycopy();", without the quotation marks, in an appropriate place inside one of the methods of the program. This is the method that will move the array values.
-
-
3
Click inside the two parentheses you typed in the last step so that the cursor is between them.
-
4
Type the name of the array that you will be moving values from, followed by a comma.
-
5
Type the index to start copying from, as an integer. This is the point in the source array where copying will begin. If you want to copy the whole array, put 0. After the number, type a comma.
-
6
Type the name of the array that you will be moving values to, followed by a comma. This array should already be declared earlier in the program.
-
7
Type the index in the destination array to start copying values to. The first copied value will go here. If you are just copying one array into another, put 0. Follow this with another comma.
-
8
Type the number of values to copy, as an integer. If you are copying the whole array, put the size of the array. Remember that you can just type the name of the array followed by ".length" to get the size. This is the last argument of the arraycopy() method.
-
1
Tips & Warnings
This method is actually making a copy, rather than moving values. The old array will remain the same afterward. You can stop using it and let it be garbage-collected if you want, or use it for other purposes.