I translated [Clone method for Java arrays] as the Clone method in Java arrays.

I found an easy-to-understand explanation for clone () in Java arrays, so I translated it.

[Quote] stackoverflow Clone method for Java arrays


When the clone method is called on an array, it returns a new instance of the same array element. For example, the following code creates different instances for ʻint [] a and ʻint [] b.


    int[] a = {1,2,3};
    int[] b = a.clone();

    * 「a == b ?Is a and b the same instance? Judgment
    System.out.println(a == b ? "Same instance":"It's a different instance");
    //Output: Different instance

Since the two are different instances, changes to int [] b will not affect int [] a.


    b[0] = 5;
    System.out.println(a[0]);
    System.out.println(b[0]);
    //output: 1
    //       : 5

This is a bit confusing when it comes to arranging objects. (For arrays) The clone method returns the reference destination of the new array. This will be the same reference as the source array object.

For example, suppose you have a Dog class.


    class Dog{

        private String name;

        public Dog(String name) {
            super();
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

    }

And I add an array of Dog class.


    Dog[] myDogs = new Dog[4];

    myDogs[0] = new Dog("Wolf");
    myDogs[1] = new Dog("Pepper");
    myDogs[2] = new Dog("Bullet");
    myDogs[3] = new Dog("Sadie");

And when you clone dog ...

    Dog[] myDogsClone = myDogs.clone();

The two refer to the same element.


    System.out.println(myDogs[0] == myDogsClone[0] ? "the same":"Wrong");
    System.out.println(myDogs[1] == myDogsClone[1] ? "the same":"Wrong");
    System.out.println(myDogs[2] == myDogsClone[2] ? "the same":"Wrong");
    System.out.println(myDogs[3] == myDogsClone[3] ? "the same":"Wrong");
    //Output: Same(4 times)

What this means is that the two are the same reference, so if you make a change to the cloned array, the change will be reflected in the original array as well.

    //Any changes you make to myDogsClone will also be reflected in the values of the elements in myDogs.
    myDogsClone[0].setName("Ruff"); 
    System.out.println(myDogs[0].getName());
    //Output: Ruff

However, if you create a new instance for the array, the changes will not affect the original instance.

    myDogsClone[1] = new Dog("Spot");
    System.out.println(myDogsClone[1].getName());
    System.out.println(myDogs[1].getName());
    //Output: Spot
    //      Pepper

I learned a lot! : relaxed:

Recommended Posts

I translated [Clone method for Java arrays] as the Clone method in Java arrays.
Call the super method in Java
Implementation of clone method for Java Record
I tried the new era in Java
What is the main method in Java?
[Java] Handling of JavaBeans in the method chain
ChatWork4j for using the ChatWork API in Java
[Java] Something is displayed as "-0.0" in the output
I want you to use Scala as Better Java for the time being
Combine arrays in Java
When I wanted to create a method for Premium Friday, it was already in the Java 8 standard API
A note for Initializing Fields in the Java tutorial
I tried using an extended for statement in Java
I tried to implement the Euclidean algorithm in Java
Review because I used the collection_check_boxes method in the Ralis portfolio
[Java] ArrayList → Should I specify the size in array conversion?
[Rails] I tried using the button_to method for the first time
I made roulette in Java.
[Android, Java] Convenient method to calculate the difference in days
Create a method to return the tax rate in Java
[Java] I implemented the combination.
In Ruby code, I was confused for a moment as "Hash-like but parentheses are arrays?"
Implement the same function as C, C ++ system ("cls"); in Java
I studied the constructor (java)
I tried metaprogramming in Java
I want to simplify the conditional if-else statement in Java
[Java] How to search for a value in an array (or list) with the contains method
I made the "Sunshine Ikezaki game" I saw on Twitter in Java.
Java14 came out, so I tried record for the time being
Defeat the hassle of treating C arrays as Tuples in Swift
I made a method to ask for Premium Friday (Java 8 version)
[Java] I tried to make a maze by the digging method ♪
[Java] I want to perform distinct with the key in the object
A story that I finally understood Java for statement as a non-engineer
Leverage Either for individual exception handling in the Java Stream API
Access the network interface in Java
I sent an email in Java
Guess the character code in Java
Rock-paper-scissors game for beginners in Java
Automatic photo resizing method in Java
I created a PDF in Java.
[For beginners] Run Selenium in Java
Specify the java location in eclipse.ini
Java comparison using the compareTo () method
Unzip the zip file in Java
I tried to explain the method
I wrote Goldbach's theorem in java
I tried the Java framework "Quarkus"
Parsing the COTOHA API in Java
I made an annotation in Java.
I tried using JWT in Java
Settings for SSL debugging in Java
How arrays work in Java (illustration)
Java12 came out, so I tried the switch expression for the time being
For the time being, run the war file delivered in Java with Docker
In DynamoDB Enhanced Client, I access the index table for some reason
I called the COTOHA API parser 100 times in Java to measure performance.
I wrote EX25 of AtCoder Programming Guide for beginners (APG4b) in java.
I want to get the IP address when connecting to Wi-Fi in Java
[Socket communication (Java)] Impressions of implementing Socket communication in practice for the first time
I translated the grammar of R and Java [Updated from time to time]