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

2017-09-26

posted Sep 26, 2017, 9:51 AM by Samuel Konstantinovich   [ updated Sep 27, 2017, 9:30 AM ]
Goal: References vs Primitives

Go Over Array Problems

A reference in java is similar to using the address in memory of the thing you are referring to. 

import java.util.Arrays;
public class ArrayDemo{

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

  public static int[][] returnCopy(int[][]ary){
    int[][] ans =  new int[ary.length][ary[0].length];
    for(int r = 0; r<ary.length; r++){
     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[] a = {1,2,3};
    int[][]data = {
      {1,0,1},
      {0,0,1},
      {1,1,3}};
    int[][]data2 = {
      {3,1,0,1},
      {4,0,0,1},
      {5,1,1,3}};
    System.out.println(toString(a));
    System.out.println(toString(data));
    

    data = returnCopy(data2);
    //data = data2;

    data[0][0]=-1000;
    System.out.println(toString(data));
    //modifyArray(data2);

    System.out.println(toString(data2));
  }
}

Comments