tronds icon

Arrays copy and reference

tronds | PRO | 09/11/13 04:24:03 PM UTC | 0 ⭐ | 200 👁️ | Never ⏰ | []
Java |

1.12 KB

|

None

|

0 👍

/

0 👎

package com.humborstad.Test_Java;
 
import java.util.Arrays;
 
 
public class Main {
    public static void main(String[] args){
        double[] originalArray = {0,1,2,3,4,5,6};
        
        //Will make a copy to the reference
        double[] referenceArray = originalArray;
        
        //Will make a true copy
        double[] trueCopyArray = Arrays.copyOf(originalArray, originalArray.length);
        
        //Lets try to modify the first reference:
        originalArray[0] = 1337;
        //We will see that this will stick to referenceArray too
        
        System.out.println("originalArray");
        for(double element : originalArray){
            System.out.println(element);
        }
        /*originalArray
        1337.0
        1.0
        2.0
        3.0
        4.0
        5.0
        6.0*/
        
        System.out.println("referenceArray");
        for(double element : referenceArray){
            System.out.println(element);
        }
        /*referenceArray
            1337.0
            1.0
            2.0
            3.0
            4.0
            5.0
            6.0*/
        
        System.out.println("trueCopyArray");
        for(double element : trueCopyArray){
            System.out.println(element);
        }
        /* Will print:
         * trueCopyArray
                0.0
                1.0
                2.0
                3.0
                4.0
                5.0
                6.0
        */
    }
}

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎