Example of clone array in Java


To making copy of array in Java, we can use method “clone” in the array objects.
First step, we need to create one-dimensional array :

1
2
// Create first array variable
float[] floatArray = {5.0f, 3.0f, 1.5f};

This will create an array objects with 3 elements. We can clone this by:

1
2
// Create clone variable
float[] cloneArray = floatArray.clone();

All modification between two variable will not related each others.
Here is the details:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.util.Arrays;

public class ArrayClone {
    public static void main(String[] args) {
        // Create first array variable
        float[] floatArray = { 5.0f, 3.0f, 1.5f };
        System.out.println(Arrays.toString(floatArray) + " – Originaln");

        // Create clone variable
        float[] cloneArray = floatArray.clone();
        System.out.println(Arrays.toString(cloneArray) + " – Clonen");

        // Modify original
        floatArray[1] = 2.2f;
        System.out.println(Arrays.toString(floatArray) + " – Originaln");
        System.out.println(Arrays.toString(cloneArray) + " – Clonen");

        // Modify clone
        cloneArray[1] = 2.1f;
        System.out.println(Arrays.toString(floatArray) + " – Originaln");
        System.out.println(Arrays.toString(cloneArray) + " – Clonen");

    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.