Click here to load reader

Java arrays: Creation (5) - University of Liverpoolcgi.csc.liv.ac.uk/~michele/TEACHING/COMP102/2006/2.4.pdf · Java arrays: Creation (6) What happens if we try to create an array

  • Upload
    others

  • View
    19

  • Download
    0

Embed Size (px)

Citation preview

  • Data Structures and Information SystemsPart 1: Data Structures

    Michele Zito

    Lecture 3: Arrays (1)

    . – p.1/74

    Topics

    Data structure definition: arrays.

    Java arrays

    creation

    access

    Primitive types and reference types

    Internal representation of Java arrays and potential pitfalls.

    . – p.2/74

    Definition

    An array is a sequence of components (of the same type) with thefollowing properties

    the length of the array equals the number of components ofthe array and is fixed when the array is createdeach component of the array has a fixed and unique indexthe indices range from a lower index bound to an upper indexboundeach component of the array can be accessed and modified(in constant time) using its index

    a . . .

    low low+1 low+2 high−2 high−1 high

    . – p.3/74

    Java arrays

    Java arrays have the following specific properties:

    For an array of length n, the lower index bound is always 0and the upper index bound is always n−1

    The notation for inspecting the length of an array a is a.length

    Every array is homogeneous, that is, the type of all itscomponents is the sameHowever, if all components are of type T , where T is anobject class, then it can store objects of any subclass of T

    The notation for accessing the component of an array a atindex i is a[i]

    . – p.4/74

  • Java arrays: Creation (1)

    The three steps for creating an array are:

    1. Defining an arrayThere are two ways to declare that a variable is an array

    i n t [ ] Array1 ;i n t Array2 [ ] ;

    both have exactly the same effectThe declaration itself does not allocate memory

    2. Allocating memory space for the array

    Array1 = new i n t [ 3 ] ;

    Only at this point will memory space be allocated.Remember that Array1 has 3 components with indices 0, 1,and 2.

    . – p.5/74

    Java arrays: Creation (2)

    The three steps for creating an array are:

    3. Initialising the components of the arrayIf we do not specify the initial values for the components ofan array, then the components are initialised with 0 or null asapplicable, but it is good practise not to rely on this feature ofJava.One way of initialising an array yourself is by specifying theinitial values for all the components of an array

    i n t [ ] Array2 = { 2 , 3 , 5 , 7 } ;

    Notice that in this case we do not and cannot specify the sizeof the array. It will automatically be inferred that Array2 has 4components with indices 0 to 3.

    . – p.6/74

    Java arrays: Creation (3)

    The first two steps of creating an array can be performed asone:

    i n t [ ] Array3 = new i n t [ 3 ] ;i n t Array4 [ ] = new i n t [ 4 ] ;

    The third step of initialising an array is optional, but can alsobe merged with the others:

    i n t [ ] Array5 = { 1 , 2 } ;i n t Array6 [ ] = { 6 , 5 , 4 } ;

    . – p.7/74

    Java arrays: Creation (4)

    In all the examples up to now we have used an integer constant asthe size of the array, but this is not necessary:

    impor t java . i o . ∗ ;

    c lass TestArray {

    p u b l i c s t a t i c BufferedReader keyboardInput =

    new BufferedReader (new InputStreamReader ( System . i n ) ) ;

    p u b l i c s t a t i c vo id main ( S t r i n g args [ ] ) throws IOExcept ion {

    System . out . p r i n t l n ( " Enter s ize o f ar ray : " ) ;

    i n t n = new In tege r ( keyboardInput . readLine ( ) ) . i n tVa lue ( ) ;

    i n t [ ] Array1 = new i n t [ n ] ;

    System . out . p r i n t l n ( " Length o f Array1 : " + Array1 . leng th ) ;

    } }

    . – p.8/74

  • Java arrays: Creation (5)Here is a transcript of a run of TestArray:

    Enter s i ze o f ar ray :2

    Length o f Array1 : 2

    The example also illustrates that arrays are allocateddynamically during the run-time of the program

    What is the minimal size of an array?It turns out that the minimal size of an array is 0

    Enter s i ze o f ar ray :0

    Length o f Array1 : 0

    However, an array of size 0 has no components. So, wecannot store anything in it.

    . – p.9/74

    Java arrays: Creation (6)What happens if we try to create an array of size -1?

    Enter s i ze o f ar ray :−1

    Except ion i n thread " main "java . lang . Negat iveArraySizeExcept ionat TestArray3 . main ( TestArray3 . java :12 )

    This leads to a run-time error that causes an exception to bethrown

    Would it make a difference if we could already see in theprogram code that a negative array size is used?

    i n t Array7 [ ] = new i n t [−1 ] ;

    No! The Java compiler will not indicate that something iswrong. We still get the same run-time error

    . – p.10/74

    Exceptions

    An exception is an event that occurs during programexecution and which makes further execution impossible

    Standard examples are divide by zero error and arithmeticoverflow, but there are many more

    An exception handler is a piece of code that gets invokedwhen an exception is encounteredIt allows the program to either fix what ever caused theexception, or abort execution gracefullyThe default exception handler just outputs an error messageand terminates the program execution

    How you write your own exception handlers will be a subjectof COMP 213

    . – p.11/74

    Java arrays: Access (1)

    One of the standard operations performed on arrays is toloop through all array elements to apply some operation toeach of them

    i n t [ ] Array2 = { 2 , 3 , 5 , 7 } ;

    f o r ( i n t i = 0 ; i < 4 ; i + + ) { System . out . p r i n t l n ( Array2 [ i ] ) ; }

    Note that this is an example of coupling: Changing thenumber of components of Array2 would require us to changethe for-loopBut this can easily be avoided using the length attribute ofarrays

    f o r ( i n t i = 0 ; i

  • Java arrays: Access (2)

    Always remember that in a Java array of size n, indices rangefrom 0 to n−1 and not from 1 to nExecuting the following program

    i n t [ ] Array2 = { 2 , 3 , 5 , 7 } ;

    f o r ( i n t i = 1 ; i

  • Primitive types and reference types (2)

    Instead of talking about memory locations we often depictthis situation as follows:

    variable

    value

    For primitive types,

    var1 == var2

    is true if the stored values for variables var1 and var2 areidentical

    . – p.17/74

    Primitive types and reference types (3)

    Remember that Java distinguishes between primitive (data)types and reference types

    Any data type that is not a primitive type is a reference type

    A variable of a reference type is not directly associated with amemory location that stores a valueInstead it is associated with a memory location that storesthe address of the memory location storing the value, that is,it stores a reference to a value

    This kind of variable is called reference variable

    . – p.18/74

    Primitive types and reference types (4)

    Instead of talking about memory locations and addresses weoften depict this situation as follows:

    variable value(s)

    . . .

    The declaration of a reference variable does not initialise thevariable with the address of some value(s)Instead, the variable is given the special value null if it is aninstance or class variable

    variable

    null

    . – p.19/74

    Primitive types and reference types (5)

    For reference types,

    var1 == var2

    is true, if both var1 and var2 store the same address(or they are both null)

    There is an alternative way to compare variables: equals

    var1.equals(var2)

    A number of classes define equals in such a way that itcompares the value found at the addresses stored in var1and var2

    However, by default, it returns the same result asvar1 == var2 (given that var1 is non-null)

    . – p.20/74

  • Internal representation of Java arrays

    Java arrays are reference types

    Example:

    T [ ] a = new T [ n ]

    Defines an array variable with name a whose componentsare of type T and allocates memory space for n suchcomponents

    a

    T[] n

    class tag length 0 1 · · · n−2 n−1

    . – p.21/74

    Equality between array variables

    A consequence of the fact that Java arrays are referencetypes is that the == operator compares references not thedata stored in arrays

    So, if we have the following two arrays

    i n t [ ] Array1 = { 2 , 3 , 5 , 7 } ;i n t [ ] Array2 = { 2 , 3 , 5 , 7 } ;

    then Array1==Array2 evaluates to false

    Unfortunately, the equals operator does not compare thedata stored in arrays either

    So, in our example Array1.equals(Array2) againevaluates to false

    . – p.22/74

    Assignments

    Another consequence of the fact that Java arrays arereference types is that an assignment statement like

    Array1 = Array2

    copies the address stored in Array2 to Array1, making bothArray1 and Array2 refer to the same object

    i n t [ ] Array1 = { 2 , 3 , 5 , 7 } ;

    i n t [ ] Array2 = { 2 , 3 , 5 , 7 , 1 1 } ;

    Array1 = Array2 ;

    Array2 [ 4 ] = 1 3 ;

    System . out . p r i n t l n ( " Array1 [ 4 ] = " + Array1 [ 4 ] ) ;

    prints out

    Array1 [ 4 ] = 1 3

    . – p.23/74

    Data Structures and Information SystemsPart 1: Data Structures

    Michele Zito

    Lecture 4: Arrays (2)

    . – p.24/74

  • Topics

    Java arrays: Access implementation

    Arrays: Advantages and disadvantages

    Enlarging arrays

    Arrays of reference types

    Arrays of string objects

    Arrays of objects

    . – p.25/74

    Internal representation of Java arrays

    Java arrays are reference types

    Example:

    T [ ] a = new T [ n ]

    Defines an array variable with name a whose componentsare of type T and allocates memory space for n suchcomponents

    a

    T[] n

    class tag length 0 1 · · · n−2 n−1

    . – p.26/74

    Java arrays: Access implementationa

    T[] n

    class tag length 0 1 · · · n−2 n−1

    Given an index i how do we work out where to look for thecomponent a[i]?

    memory location of a[i] = value of variable a

    + size of class tag T[]

    + size of length attribute

    + (i× size of component)

    This computation can be done in constant time(i.e. the computation is so fast that, approximately, we may say thatit takes an amount of time that is independent of the size of thearray).

    . – p.27/74

    Arrays: Advantages and disadvantages

    Arrays, including Java arrays, are static data structures sincethe number of elements they can store is fixed at the time ofcreation

    As such they inherit all the advantages and disadvantages ofstatic data structures

    . – p.28/74

  • Arrays: Advantages

    Easy to specify(declaration, allocation of memory space, initialisation can allbe done in one line of code)

    There is no run-time overhead to allocate/free memory(apart from once at the start and end)

    Random (direct) access to any element via the index

    e.g. direct access to a student record via student number(index can be derived from student number)

    It is usually faster to sequentially access elements than, forexample, in linked lists, due to

    contiguous storage (good locality) andconstant time computation of the address of acomponent

    . – p.29/74

    Arrays: Disadvantages

    A potential disadvantage of arrays (depending on theapplication) is the need to know the size at the time ofallocation.

    Careful design is required to make sure that the array will belarge enough to hold the largest possible group of data butno larger

    Can we find a workaround for this problem?

    Yes, if more elements are required than an array is able to store,

    then a new larger array needs to be created and the data trans-

    ferred across.

    . – p.30/74

    Enlarging arrays

    Assume that oldArray is an integer array which is too small for thenumber of elements we want to store in itThe following code replaces oldArray by an array of twice the sizeof the original array

    i n t o ldSize = o ldAr ray . leng th ;

    i n t newSize = 2 ∗ o ldAr ray . leng th ;

    i n t [ ] newArray = new i n t [ newSize ] ;

    f o r ( i n t i = 0 ; i

  • Arrays as method arguments (2)

    Now we use this method in a program:

    impor t java . i o . ∗ ;

    c lass TestArray5 {

    p u b l i c s t a t i c i n t [ ] doubleSize ( i n t [ ] o ldAr ray ) {

    . . .

    }

    p u b l i c s t a t i c vo id main ( S t r i n g args [ ] ) {

    i n t [ ] primes = { 2 , 3 , 5 } ;

    i n t o ldSize = primes . leng th ;

    primes = doubleSize ( primes ) ;

    primes [ o ldSize ] = 7 ;

    f o r ( i n t i = 0 ; i

  • Arrays of string objects: Creation

    A particular reference type we already know is String

    So,

    S t r i n g [ ] words = new S t r i n g [ 4 ] ;

    creates an array of strings with four components

    Remember, this declaration does not allocate any memoryspace for the strings, it only allocates space for an arraystoring four memory locations (of strings)

    Also, all the components are initialised with the nullreference, not with an empty string

    . – p.37/74

    Arrays of string objects: Storing strings

    Next, let us store strings in our array of strings

    words [ 1 ] = " t im " ;words [ 2 ] = " tom " ;words [ 3 ] = " t im " ;

    Remember, "tim" and "tom" are so-called string literals

    Are words[1] and words[3] equal?

    Both words[1] == words[3]as well as words[1].equals(words[3]) return true!

    This is due to the compiler which only creates one internalstring object for both occurrences of "tim" in our code

    . – p.38/74

    Arrays of objects: Creation

    The most general kind of array would have components oftype Object

    The Object class is located at the top of the Java classhierarchyEvery Java class is a descendant, direct or indirect, of theObject class, but not the primitive data types

    We can declare an array with components of type Object asfollows:

    Object [ ] ob jAr ray = new Object [ 3 ] ;

    . – p.39/74

    Arrays of objects: Storing objects

    In the components of objArray we can now store objects ofany subclass of Object

    ob jAr ray [ 0 ] = " t im " ;ob jAr ray [ 1 ] = new BasicBox ( 1 , 2 , 3 ) ;

    Remember that BasicBox is a class that we have definedearlierWe assume that the definition of the BasicBox class isextended by

    p u b l i c S t r i n g t o S t r i n g ( ) {

    r e t u r n ( " box ( "+ depth + " , " + he igh t + " , " + width + " ) " ) ;

    }

    which overrides the default method for providing a Stringrepresentation of an object

    . – p.40/74

  • Arrays of objects: Storing primitive data

    But, unfortunately, we cannot directly store an element of aprimitive data type in itIncluding the following code

    ob jAr ray [ 2 ] = 5 ;

    into our program results in the following error message by thecompiler:

    TestObjectArray . java : 1 2 : incompat ib le typesfound : i n trequ i red : java . lang . Object

    ob jAr ray [ 2 ] = 5 ;^

    1 e r r o r

    . – p.41/74

    Arrays of objects: Storing primitive data

    To store an integer value like 5 in objArray we have to makeuse of a wrapper class

    Each of the primitive data types like char or int has acorresponding wrapper class associated with it, namedCharacter, Integer, etc.

    Each of these classes wraps a primitive data type into aclass which in turn is a subclass of Object

    So,

    ob jAr ray [ 2 ] = new In tege r ( 5 ) ;

    wraps the number 5 into an object of class Integer, which canbe assigned to a component of objArray

    . – p.42/74

    Arrays of objects: Accessing (1)

    To access all the components of an array of reference typeswe can use the same code that we have used for integerarrays

    f o r ( i n t i = 0 ; i

  • Arrays of objects: Accessing (3)

    Instead, we have to unwrap the Integer object first, to get theinteger value back

    Unfortunately, the straightforward approach

    i n t n = 3+ ob jAr ray [ 2 ] . i n tVa lue ( ) ;

    produces again an error message by the compiler:

    TestObjectArray . java : 1 7 : cannot reso lve symbolsymbol : method in tVa lue ( )l o c a t i o n : c lass java . lang . Object

    i n t n = 3 + ob jAr ray [ 2 ] . i n tVa lue ( ) ;

    The compiler only knows that the components of objArraybelong to class ObjectIt does not know that objArray[2] belongs to Integer

    . – p.45/74

    Arrays of objects: Accessing (4)

    One way of solving this problem is to use typecasting:We typecast objArray[2] from the Object class to itssubclass Integer

    Once this is done, we can use the intValue method of theInteger class to retrieve the actual integer value

    i n t n = 3 + ( ( In tege r ) ob jAr ray [ 2 ] ) . i n tVa lue ( ) ;System . out . p r i n t l n ( " n = " + n ) ;

    produces the output

    n = 8

    . – p.46/74

    Data Structures and Information SystemsPart 1: Data Structures

    Michele Zito

    Lecture 5: Multi-dimensional arrays

    . – p.47/74

    Topics

    Multi-dimensional arrays: Examples of applications

    Multi-dimensional array, definition

    2-dimensional arrays in Java

    Access implementationCreationCloningAccess

    2-dimensional arrays as method arguments

    Higher-dimensional arrays in Java

    Example: Train departure information

    . – p.48/74

  • (Linear) Arrays

    An array is a sequence of indexed components.

    a . . .

    low low+1 low+2 high−2 high−1 high

    In many applications it is more logical to think of the data in a tableform instead of a linear list:

    timetable

    chess board

    distances between cities

    theatre seating layout

    . – p.49/74

    2-D organisation: Examples (1)

    Other, perhaps less obvious applications:

    Crosswords

    O R T H O D O X Y C O N

    N E R D E H O

    L A N C E D I S D A I N

    Y S E T O P

    C I R C U S E A S E L

    O O T R U

    L A N I M A E D I C T S

    A P T A L

    R E E V E H O Y D E N

    A X L E A G

    C H A B L I S E L V E R

    H C E I T E I

    S E T D E S P A I R E D . – p.50/74

    2-D organisation: Examples (2)

    Images

    rows of columns of pixels (picture elements)

    each pixel has a valuebinary images: black - 0, white - 1greyscale: from black to white - 0..255each pixel is identifiable by its 2-D coordinates(row number and column number)

    . – p.51/74

    3-D organisation: Examples

    3-D graphics

    e.g., location of objects within a room

    3-D medical imaging

    a stack of 2-D slices (images)

    Colour images

    three two-dimensional arrays (one array storing the redvalue of each pixel in its components, the other twoarrays do the same for the green and blue value) or

    one two-dimensional array where each component is aone-dimensional array (storing the red, green, and bluevalue of a single pixel)

    . – p.52/74

  • Multi-dimensional array

    A multi-dimensional array is a collection of components indexed byunique integer sequences of fixed length with the followingproperties:

    the length of an index sequence is the rank or number ofdimensions of a multi-dimensional array

    for each dimension d there is a lower index bound ld and ahigher index bound hdfor an array of dimension n, an index is an integer sequencewritten [i1] . . . [in] such that for every dimension d,ld ≤ id ≤ hdany component of the array can be accessed and modified in“constant” time using its index

    . – p.53/74

    Multi-dimensional arrays: Example

    Here is an example of a 2-dimensional array:

    a l2 l2+1 . . . h2−1 h2

    l1 a[l1][l2] a[l1][h2]

    l1+1...

    h1−1

    h1 a[h1][l2] a[h1][h2]

    The fact that we have drawn the first dimension in vertical direction

    and the second dimension in horizontal direction has no particular

    importance. – p.54/74

    2-dimensional arrays in JavaJava does not actually support 2-dimensional (or higherdimensional) arrays as such

    We can achieve the same effect, though, using a1-dimensional array whose components are 1-dimensionalarrays

    i n t [ ] [ ] a = new i n t [ 3 ] [ 4 ]

    a

    0

    1

    2

    0 1 2 3class

    tag

    leng

    th

    class taglength

    a[0] is a1-dimensional array

    a[0][0] is aninteger component

    . – p.55/74

    Access implementation (1)

    How does Java find the memory location of a component a[i][j] in a2-dimensional array a?

    1. Locate a[i] using the function

    memory location of a[i] = value of variable a

    + size of class tag of a

    + size of length attribute

    + (i× size of an address)

    2. Retrieve the value of a[i]We know that a[i] stores the memory location (address) ofthe 1-dimensional array storing a[i][j]

    . – p.56/74

  • Access implementation (2)

    How does Java find the memory location of a component a[i][j] ofa 2-dimensional array a?

    3. Locate a[i][j] using the function

    memory location of a[i][j] = value of variable a[i]

    + size of class tag of a[i]

    + size of length attribute

    + (j× size of component)

    Note that if a[i][j] is of reference type, then the size of acomponent is again the size of an address

    . – p.57/74

    Access implementation: Properties

    This algorithm can easily be generalised to arrays of arbitrarydimensionalityFor example, for a 3-dimensional array we have to perform 5steps to locate a[i][j][k]:

    1. Locate a[i]2. Retrieve a[i]3. Locate a[i][j]

    4. Retrieve a[i][j]5. Locate a[i][j][k]

    The algorithm is executed during run-time each time we needa[i][j][k].

    . – p.58/74

    2-dimensional arrays in Java: Creation (1)

    Just as for 1-dimensional arrays, the three steps for creating a2-dimensional array are:(1) Defining an array,(2) Allocating memory space for an array, and(3) Initialising an array

    1. Defining a 2-dimensional arrayThere are two ways to declare that a variable is a2-dimensional array

    i n t [ ] [ ] Array1 ;i n t Array2 [ ] [ ] ;

    both have exactly the same effectThe declaration itself does not allocate memory

    . – p.59/74

    2-dimensional arrays in Java: Creation (2)

    2. Allocating memory space for a 2-dimensional array

    Array1 = new i n t [ 3 ] [ 4 ] ;

    Only at this point will memory space be allocated.

    Array1 is a 1-dimensional array with three components,each component itself is (a reference to) a 1-dimensionalarray with four components of type int

    Alternatively, we can view Array1 as a 2-dimensionalarray which has 3 rows (0, 1, and 2) and 4 columns (0, 1,2, 3) and each component has type int

    However, always remember that this is an abstraction ofthe true internal structure of 2-dimensional arrays in Java

    . – p.60/74

  • 2-dimensional arrays in Java: Creation (3)

    3. Initialising the components of a 2-dimensional array

    Unless we specify initial values for the components of a2-dimensional array ourselves, then the component areinitialised with 0 or null

    Remember that

    S t r i n g [ ] [ ] Array3 = new S t r i n g [ 2 ] [ 3 ] ;

    creates a 2-dimensional array with components of typeString which are initialised to null, not to the empty string

    . – p.61/74

    2-dimensional arrays in Java: Creation (4)

    One way of initialising an array ourselves is by specifyingthe initial values for all the components of an array:

    i n t [ ] [ ] Array2 = { { 1 0 , 1 2 , 1 4 } ,{ 2 0 , 2 2 , 2 4 } } ;

    The result will be

    Array2[0][0] = 10 Array2[0][1] = 12 Array2[0][2] = 14

    Array2[1][0] = 20 Array2[1][1] = 22 Array2[1][2] = 24

    or, in form of a diagram:

    0 1 2

    0 10 12 14

    1 20 22 24

    . – p.62/74

    2-dimensional arrays in Java: Creation (5)

    Instead of

    i n t [ ] [ ] Array2 = { { 1 0 , 1 2 , 1 4 } ,{ 2 0 , 2 2 , 2 4 } } ;

    we could also use existing arrays for initialisation:

    i n t [ ] Array4 = { 1 0 , 1 2 , 1 4 } ;i n t [ ] Array5 = { 2 0 , 2 2 , 2 4 } ;Array2 = { Array4 , Array5 } ;

    However, this might not have the effect you want

    Note that Array2 now does not store copies of Array4and Array5 in Array2[0] and Array2[1], respectively

    Instead it stores references to the already existing Array4and Array5 in Array2[0] and Array2[1], respectively

    . – p.63/74

    2-dimensional arrays in Java: Creation (6)

    Consequently, if we change, for example, Array4[1], wealso change Array2[0][1]:

    Array4 [ 1 ] = 5 1 ;

    System . out . p r i n t l n ( " Array2 [ 0 ] [ 1 ] = " + Array2 [ 0 ] [ 1 ] ) ;

    prints out

    Array2 [ 0 ] [ 1 ] = 5 1

    To create copies of already existing 1-dimensionalarrays, we can use the clone method:

    i n t [ ] Array4 = { 1 0 , 1 2 , 1 4 } ;

    i n t [ ] Array5 = { 2 0 , 2 2 , 2 4 } ;

    i n t [ ] [ ] Array2 = { ( i n t [ ] ) Array4 . clone ( ) ,

    ( i n t [ ] ) Array5 . clone ( ) } ;

    . – p.64/74

  • 2-dimensional arrays in Java: Cloning

    Be careful: It is possible to clone multi-dimensional arrays aswell, but the clone is shallow

    Remember that multi-dimensional arrays in Java are arraysof arrays of arrays . . .Cloning only generates a copy of the root array

    For example, in a 2-dimensional array

    i n t [ ] [ ] Array2 = { { 1 0 , 1 2 , 1 4 } ,{ 2 0 , 2 2 , 2 4 } } ;

    Array2[0] and Array2[1] form an 1-dimensional array thatstores the memory locations m0 and m1 of two 1-dimensionalarrays

    If we clone Array2, then we only create a new 1-dimensionalarray that again stores m0 and m1

    . – p.65/74

    2-dimensional arrays in Java: Access (1)

    While we have used a single for-loop to access all thecomponents of an 1-dimensional array, we can use twonested for-loops to do the same for a 2-dimensional array:

    f o r ( i n t i = 0 ; i < Array2 . leng th ; i + + ) {

    f o r ( i n t j = 0 ; j < Array2 [ i ] . leng th ; j ++)

    System . out . p r i n t ( " Array2 [ " + i + " ] [ " + j + " ] = "

    + Array2 [ i ] [ j ] + " , " ) ;

    System . out . p r i n t ( " \ n " ) ;

    }

    prints out

    Array2 [ 0 ] [ 0 ] = 1 0 , Array2 [ 0 ] [ 1 ] = 1 2 , Array2 [ 0 ] [ 2 ] = 1 4 ,

    Array2 [ 1 ] [ 0 ] = 2 0 , Array2 [ 1 ] [ 1 ] = 2 2 , Array2 [ 1 ] [ 2 ] = 2 4 ,

    . – p.66/74

    2-dimensional arrays in Java: Access (2)

    f o r ( i n t i = 0 ; i < Array2 . leng th ; i + + ) {

    f o r ( i n t j = 0 ; j < Array2 [ i ] . leng th ; j ++)

    System . out . p r i n t ( " Array2 [ " + i + " ] [ " + j + " ] = "

    + Array2 [ i ] [ j ] + " , " ) ;

    System . out . p r i n t ( " \ n " ) ;

    }

    Note that we use Array2.length to determine the number ofrows of Array2 in the outer for-loop

    And we use Array2[i].length to determine the number ofcolumns of the 1-dimensional array stored in Array2[i] in theinner for-loop

    Note also, the use of i in Array2[i].length means that there isno easy way to swap the two loops

    . – p.67/74

    2-dimensional arrays as method arguments

    Initialising the component with index [i][j] in a 2-dimensional arraywith (i+1)*(j+1)

    In Java this is a trivial exercise:

    p u b l i c s t a t i c vo id i n i t A r r a y ( i n t Array [ ] [ ] ) {f o r ( i n t i = 0 ; i < Array . leng th ; i ++)

    f o r ( i n t j = 0 ; j < Array [ i ] . l eng th ; j ++)Array [ i ] [ j ] = ( i +1)∗ ( j +1 ) ;

    }

    This method works since

    Any argument will be passed to this method usingcall-by-referenceJava will only compute at run-time what the memory locationof Array[i][j] is

    . – p.68/74

  • Higher-dimensional arrays in Java

    Java permits arrays of three, four or more dimensions

    The way these arrays are created is a straightforwardgeneralisation of the way 2-dimensional arrays are created

    Here is an example of the creation of a 3-dimensional array:

    c lass F i l l 3DAr ray {

    p u b l i c s t a t i c vo id main ( S t r i n g args [ ] ) {

    i n t [ ] [ ] [ ] M = new i n t [ 3 ] [ 4 ] [ 2 ] ;

    f o r ( i n t row = 0 ; row < M. leng th ; row++)

    f o r ( i n t co l = 0 ; co l < M[ row ] . leng th ; co l ++)

    f o r ( i n t ver = 0 ; ver < M[ row ] [ co l ] . leng th ; ver ++)

    M[ row ] [ co l ] [ ver ] = row+co l +ver ;

    } }

    . – p.69/74

    Example: Train departure information

    We want to develop a very simple information system fortrain departure information at Liverpool Lime Street Station

    The information is given in form of a table

    Time Destination Track

    9:10 Manchester 6

    9:15 Leeds 10

    9:20 Nottingham 7

    The only kind of query we deal with is ‘When and wheredoes the next train to X leave?’

    . – p.70/74

    Train departure information: The code (1)

    impor t java . i o . ∗ ;

    c lass TDI {

    s t a t i c S t r i n g [ ] [ ] t d i = { { " 9 : 1 0 " , " Manchester " , " 6 " } ,

    { " 9 : 1 5 " , " Leeds " , " 1 0 " } ,

    { " 9 : 2 0 " , " Nottingham " , " 7 " } } ;

    p u b l i c s t a t i c S t r i n g [ ] searchDest ( S t r i n g dest ) {

    S t r i n g [ ] r e s u l t = n u l l ;

    f o r ( i n t i = 0 ; i < t d i . leng th ; i ++)

    i f ( t d i [ i ] [ 1 ] . equals ( dest ) ) {

    r e s u l t = new S t r i n g [ 2 ] ;

    r e s u l t [ 0 ] = t d i [ i ] [ 0 ] ;

    r e s u l t [ 1 ] = t d i [ i ] [ 2 ] ;

    r e t u r n r e s u l t ; } ;

    r e t u r n r e s u l t ; }. – p.71/74

    Train departure information: The code (2)

    p u b l i c s t a t i c vo id main ( S t r i n g args [ ] ) throws IOExcept ion

    {

    InputStreamReader inpu t = new InputStreamReader ( System . i n ) ;

    BufferedReader keyboardInput = new BufferedReader ( i npu t ) ;

    System . out . p r i n t l n ( " Where do you want to go ? " ) ;

    S t r i n g [ ] i n f o = searchDest ( keyboardInput . readLine ( ) ) ;

    i f ( i n f o == n u l l )

    System . out . p r i n t l n ( " Sorry , no t r a i n to t h i s d e s t i n a t i o n " ) ;

    e lse

    System . out . p r i n t l n ( i n f o [ 0 ] + " depar t ing a t t r a ck " + i n f o [ 1 ] ) ;

    } }

    . – p.72/74

  • Train departure information: ScriptHere are two runs of the program:

    Information successfully retrieved

    Where do you want to go?Leeds9:15 departing at track 10

    No information found

    Where do you want to go?YorkSorry, no train to this destination

    . – p.73/74

    TopicsDefinitionJava arraysJava arrays: Creation (1)Java arrays: Creation (2)Java arrays: Creation (3)Java arrays: Creation (4)Java arrays: Creation (5)Java arrays: Creation (6)ExceptionsJava arrays: Access (1)Java arrays: Access (2)Java arrays: Access (3)The Array Data Structure and Java arraysPrimitive types and reference types (1)Primitive types and reference types (2)Primitive types and reference types (3)Primitive types and reference types (4)Primitive types and reference types (5)Internal representation of Java arraysEquality between array variablesAssignmentsTopicsInternal representation of Java arraysJava arrays: Access implementationArrays: Advantages and disadvantagesArrays: AdvantagesArrays: DisadvantagesEnlarging arraysArrays as method arguments (1)Arrays as method arguments (2)Arrays as method arguments (3)Static data structures againArrays of reference typesArrays of string objects: CreationArrays of string objects: Storing stringsArrays of objects: CreationArrays of objects: Storing objectsArrays of objects: Storing primitive dataArrays of objects: Storing primitive dataArrays of objects: Accessing (1)Arrays of objects: Accessing (2)Arrays of objects: Accessing (3)Arrays of objects: Accessing (4)Topics(Linear)Arrays2-D organisation: Examples (1)2-D organisation: Examples (2)3-D organisation: ExamplesMulti-dimensional arrayMulti-dimensional arrays: Example2-dimensional arrays in JavaAccess implementation (1)Access implementation (2)Access implementation: Properties2-dimensional arrays in Java: Creation (1)2-dimensional arrays in Java: Creation (2)2-dimensional arrays in Java: Creation (3)2-dimensional arrays in Java: Creation (4)2-dimensional arrays in Java: Creation (5)2-dimensional arrays in Java: Creation (6)2-dimensional arrays in Java: Cloning2-dimensional arrays in Java: Access (1)2-dimensional arrays in Java: Access (2)2-dimensional arrays as method argumentsHigher-dimensional arrays in JavaExample: Train departure informationTrain departure information: The code (1)Train departure information: The code (2)Train departure information: Script