Courses‎ > ‎AP Computer Science‎ > ‎Konstantinovich‎ > ‎

2018-09-26

posted Sep 28, 2018, 6:05 AM by Konstantinovich Samuel   [ updated Sep 28, 2018, 6:05 AM ]
Demo in class:

What happens in arrayCopy when you change it as follows:
    int[][] ans =  new int[ary.length][];
    for(int r = 0; r<ary.length; r++){
      ans[r] = ary[r];
    }
    return ans;
    

public class ArrayDemo{

  public static String toString(int[]ary){
    String res = "{";
    for(int i = 0; i < ary.length; i++){
      res+=ary[i];
      if(i<ary.length-1){
        res+=", ";
      }
    }
    return res+"}";
  }




  public static String toString(int[][]ary){
    String res = "{";
    for(int i = 0; i < ary.length; i++){
      res+=toString(ary[i]);
      if(i<ary.length-1)res+=", \n";
    }
    return res+"}";
  }

  public static int[][] returnCopy(int[][]ary){
    int[][] ans =  new int[ary.length][];
    for(int r = 0; r<ary.length; r++){
      ans[r] =new int[ary[r].length];
      for(int c = 0; c<ary[r].length; c++){
         ans[r][c] = ary[r][c];
      }
    }
    return ans;
  }

  public static void modifyArray(int[][]ary){
    for(int r = 0; r<ary.length; r++){
     for(int c = 0; c<ary[r].length; c++){
       ary[r][c]=99;
     }
    }
  }

  public static void main(String[]args){

    int[][]data1 = {
      {1,2,3,4},
      {5,6,7,8}};
    int[][] data2 = data1;
    int[][] data3 = returnCopy(data2);





    System.out.println("data1 is a 2d array with values set");
    System.out.println("data2 = data1");
    System.out.println("data3 = COPY OF data1");
    System.out.println("they all look the same now:");
    System.out.println("data1 :\n"+toString(data1));
    System.out.println("data2 :\n"+toString(data2));
    System.out.println("data3 :\n"+toString(data3));
    System.out.println("but look at their addresses:");
    System.out.println(data1);//print the addresses
    System.out.println(data2);
    System.out.println(data3);

    System.out.println("change data1[0][0] and data2[1][3]");
   
    data1[0][0]=-999;
    data2[1][3]=-888;

    //which of these change? how do they change?
    System.out.println("data1 :\n"+toString(data1));
    System.out.println("data2 :\n"+toString(data2));
    System.out.println("data3 :\n"+toString(data3));

  }
}





Comments