(c) Copyright 1998, 1999, 2000, 2001, 2002, 2003, 2004 by Daniel Berleant  

 



 

Announcements:

   

Today: arrays

  

 

 

 


 


 

Arrays in Java


Create an array in two steps:

    1) Make a pointer to it

    2) Make the array itself at the end of the pointer

 

In more detail:

1) Make a pointer to it

 

        char myChar;

        char[ ]myArray;

        String[ ]yourArray;

        String yourArray[ ]; //[] ... same effect!

        String[ ][ ]yourArray; //2-D

        String yourArray[ ][ ]; //2-D

        String[ ]yourArray[ ];//2-D (actually works)

        String[ ][ ]yourArray=new String[5][5;]

                                      int myNum=5;

                       

        Note that you new an array

        An array is an object!

               (unlike C/C++) 

        Therefore an array name is 

            a handle (pointer) to 

            a chunk of memory

                This memory must be new'ed

                (If not new'ed the array name is a null pointer)

 

2) Make the array itself at the end of the pointer

myArray=new char[100];    

yourArray=new String[100];

 

Why? Because myArray is

-         A “handle”

-         (A pointer)

-         If you didn’t new space ... then

        char[ ]myArray;

            myArray[0];

     would give

  …a null pointer reference error

-         The new operation allocated memory for 100 char's

-         The assignment ("=")made myArray point to the memory

You can do both steps at once

 

Example:
 

char [ ] myarray=new char[100];

Let's draw a memory diagram...

What happens if you try printing myArray[100] in C?

         (Recall: 100 things are indexed 0-99!)

  

 in Java: out-of-bounds run time error

 Which way is better?

 

 In Java, you declare an array handle (pointer)

 

 . . . later, define size when allocating memory

 

 An array name is a pointer 

    …to the memory holding the array

 

 . . . if no memory allocated, handle is a null pointer

 

 Another way to solve:

 

 . . . myArray=yourArray

 

   (Assumes yourArray already refers to something . . .)

 

 Let's draw what that looks like in memory, then …

try changing myArray and then printing yourArray...

 

 Arrays can contain char's, etc.

 

 Arrays can contain complex things too

      ... String's, TrafficLight's, Label's, TextField's, other arrays, etc.

 

 Notes:

 1) Must allocate the array before assigning to its elements

 

       2) If array is of objects (rather than char, int, etc.)

             . . . you must allocate each object individually

                      An array of 100 TrafficLights…

                      …101 calls to new

                      - a hundred for the lights and one for the array

                      No need to call new for a char,int, etc.)

                                 Why? No pointers or objects involved

 

                      An array of 100 int

                      … requires just one call to new

 

 Let's look at memory diagrams for

    - an array of simple elements 

       int [ ]nums=new int[3];

 

    - an array of objects, after each statement

   String[ ]names;

   names=new String[3];

   names[0]=new String("Jo");

   names[1]=new String("Joe");

   names[2]=new String("Joan");

        

 Objects: String, trafficLight,

  Textfield, other arrays, etc.

 

 Exercise: draw diagrams for

 (a) After declaring an array str of 3 String's

 (b) After allocating memory for it

 (c) After allocating memory for one of the actual strings

 

What about an array of TrafficLight?

   (Here is a TrafficLight example:)

 
public class SimpleExample
   {
   public static void main(String args[])
     {
     TrafficLight LincolnAndWelch 
        = new TrafficLight( );
     TrafficLight RockAndBlock 
        = new TrafficLight( );
     TrafficLight allAmesLights [ ]
        = new TrafficLight [150];
     for (int count=0; count<150; count++)
        allAmesLights[count]=new TrafficLight( );
     System.out.print
        ("Intersection LincolnAndWelch:"
        + " color on Lincoln is ");
     System.out.println
        (LincolnAndWelch.color);
     System.out.print
        ("Intersection RockAndBlock:"
        + " color on Rock is ");
     System.out.println
        (RockAndBlock.color);
     }
   }
 
class TrafficLight{
  String color;
  TrafficLight( ){
    color="Red";
  }
};

 

 

 

 


 


 

Call by Value Vs. Call by Reference


 In Java, methods are called with a parameter list (in parentheses)

  A simple variable has its value passed

          i.e. the method uses a local copy

  An object has a reference (handle, pointer) passed

  . . . the method uses the actual object

         (not a copy)

This is similar to C

 


...and here is code illustrating the points so far...

 
import java.lang.*;
import TrafficLight;
public class LightArray
{
  String str;
  public static void main
          (String [ ]args)
     {
     char [ ]myArray;
     myArray=new char[7];
     // The following does the same 
     //as the two foregoing statements
     //char [ ]myArray=new char[7];
     myArray[0]='a'; 
     myArray[1]='b'; 
     myArray[2]='c'; 
     myArray[3]='d'; 
     myArray[4]='e'; 
     myArray[5]='f'; 
     myArray[6]='g'; 
     System.out.println(myArray); 
     char [ ] yourArray;
     yourArray=myArray;
     System.out.println(yourArray);
     myArray[0]='Z';
     System.out.println(yourArray);
     String [ ]arrayOfString;
     arrayOfString=new String[5];
     System.out.println
       (arrayOfString[0]);
     arrayOfString[0]
       =new String
              ("Affirmative, Captain.");
     System.out.println(arrayOfString[0]);
     System.out.println(arrayOfString[1]);
     for (int counter=0; 
          counter<5; 
          counter++)
       arrayOfString[counter]
       =new String( );
     System.out.print("****");
     System.out.print(arrayOfString[1]);
     System.out.println("####");
     TrafficLight [ ]TrafficLightArray
        =new TrafficLight[500];
     for (int counter=0; 
          counter<500; 
          counter++)
        TrafficLightArray[counter]
        =new TrafficLight( );
     System.out.println
       (TrafficLightArray[250].color);
       int someNum=5;
     int [ ]someNums=new int[500];
     myMethod(someNum, someNums);
     System.out.println(someNum);
     System.out.println(someNums[0]);
   }
   static void myMethod (int num, int [ ]Nums){
     num=10;
     Nums[0]=10;
   }
}
 

 

 


 


 

2-D Arrays


 

 A 2-D array is a 1-D array of 1-D arrays

 (array of arrays)

 Let's draw a memory diagram

 Example program:

 

import java.lang.*;
import TrafficLight;//assumes .class file exists
 
public class Array2d
{
  String str;
  public static void main
            (String [ ]args)
     {
     TrafficLight [ ][ ]myArray;
     myArray=new TrafficLight[3][3];
     //myArray=new 
     //  TrafficLight[1000][1000];
     myArray[0][0]=new TrafficLight( );
     myArray[0][1]=new TrafficLight( );
     myArray[0][2]=new TrafficLight( );
     myArray[1][0]=new TrafficLight( );     
     myArray[1][1]=new TrafficLight( );
     myArray[1][2]=new TrafficLight( );
     myArray[2][0]=new TrafficLight( );
     myArray[2][1]=new TrafficLight( );
     myArray[2][2]=new TrafficLight( );
                                                                      // NOTE: @111f71 is a memory location
                                         // Your memory location may be different
     System.out.println(myArray);        // [[LTrafficLight;@111f71
 
     System.out.println(myArray[0]);     // [LTrafficLight;@273d3c
     System.out.println(myArray[1]);     // [LTrafficLight;@256a7c
     System.out.println(myArray[2]);     // [LTrafficLight;@720eeb
 
     System.out.println(myArray[0][0]);  // TrafficLight@3179c3
     System.out.println(myArray[0][1]);  // TrafficLight@310d42
     System.out.println(myArray[0][2]);  // TrafficLight@5d87b2
     System.out.println(myArray[1][0]);  // TrafficLight@77d134
     System.out.println(myArray[1][1]);  // TrafficLight@47e553
     System.out.println(myArray[1][2]);  // TrafficLight@20c10f
     System.out.println(myArray[2][0]);  // TrafficLight@62eec8
     System.out.println(myArray[2][1]);  // TrafficLight@2a9835
     System.out.println(myArray[2][2]);  // TrafficLight@6ec612
 
     System.out.println
       (myArray[0][0].color);            // Red
     System.out.println
       (myArray[0][1].color);            // Red
     }
}