tronds

Arrays copy and reference

Sep 11th, 2013
309
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.12 KB | None | 0 0
  1. package com.humborstad.Test_Java;
  2.  
  3. import java.util.Arrays;
  4.  
  5.  
  6. public class Main {
  7.     public static void main(String[] args){
  8.         double[] originalArray = {0,1,2,3,4,5,6};
  9.        
  10.         //Will make a copy to the reference
  11.         double[] referenceArray = originalArray;
  12.        
  13.         //Will make a true copy
  14.         double[] trueCopyArray = Arrays.copyOf(originalArray, originalArray.length);
  15.        
  16.         //Lets try to modify the first reference:
  17.         originalArray[0] = 1337;
  18.         //We will see that this will stick to referenceArray too
  19.        
  20.         System.out.println("originalArray");
  21.         for(double element : originalArray){
  22.             System.out.println(element);
  23.         }
  24.         /*originalArray
  25.         1337.0
  26.         1.0
  27.         2.0
  28.         3.0
  29.         4.0
  30.         5.0
  31.         6.0*/
  32.        
  33.         System.out.println("referenceArray");
  34.         for(double element : referenceArray){
  35.             System.out.println(element);
  36.         }
  37.         /*referenceArray
  38.             1337.0
  39.             1.0
  40.             2.0
  41.             3.0
  42.             4.0
  43.             5.0
  44.             6.0*/
  45.        
  46.         System.out.println("trueCopyArray");
  47.         for(double element : trueCopyArray){
  48.             System.out.println(element);
  49.         }
  50.         /* Will print:
  51.          * trueCopyArray
  52.                 0.0
  53.                 1.0
  54.                 2.0
  55.                 3.0
  56.                 4.0
  57.                 5.0
  58.                 6.0
  59.         */
  60.     }
  61. }
Advertisement
Comments
  • Comment was deleted
Add Comment
Please, Sign In to add comment