Arrays
The Arrays class
Copy
How to copy arrays
- To copy the elements of one array into another with Java 1.5 or earlier, use the arraycopy method of the System class.
- To copy the elements of an array into another with Java 1.6 or later, use the copyOf or copyOfRange methods of the Arrays class.
- When you copy an array, the target array must be the same type as the sending array and it must be large enough to receive all of the elements that are copied to it.
How to copy an array with JDK 1.6 or later
Example 3: Copying the values of an array double[] grades = {92.3, 88.0, 95.2, 90.5}; double[] percentages = Arrays.copyOf(grades, grades.length); percentages[1] = 70.2; // doesn't change grades[1] System.out.println("grades[1]=" + grades[1]); // prints 88.0 Example 4: Copying part of one array into another array double[] grades = {92.3, 88.0, 95.2, 90.5}; Arrays.sort(grades); double[] lowestGrades = Arrays.copyOfRange(grades, 0, 2); double[] highestGrades = Arrays.copyOfRange(grades, 2, 4);
How to copy an array prior to JDK 1.6
The syntax of the arraycopy method of the System class System.arraycopy(fromArray, intFromIndex, toArray, intToIndex, intLength); Example 5: Copying the values of an array double[] grades = {92.3, 88.0, 95.2, 90.5}; double[] percentages = new double[grades.length]; System.arraycopy(grades, 0, percentages, 0, grades.length); percentages[1] = 70.2; // doesn't change grades[1] System.out.println("grades[1]=" + grades[1]); // prints 88.0 Example 6: Copying part of one array into another array double[] grades = {92.3, 88.0, 95.2, 90.5}; Arrays.sort(grades); double[] lowestGrades = new double[2]; System.arraycopy(grades, 0, lowestGrades, 0, 2); double[] highestGrades = new double[2]; System.arraycopy(grades, 2, highestGrades, 0, 2);