Topics. Java arrays. Definition. Data Structures and Information Systems Part 1: Data Structures. Lecture 3: Arrays (1)

Similar documents
Announcements. Prelude (2) Prelude (1) Data Structures and Information Systems Part 1: Data Structures. Lecture 6: Lists.

Declarations and Access Control SCJP tips

Introduction to Programming Using Java (98-388)

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

OCA Java SE 7 Programmer I Certification Guide By Mela Gupta. Arrays

Array. Prepared By - Rifat Shahriyar

School of Informatics, University of Edinburgh

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

COP 3330 Final Exam Review

Lecture Notes on Memory Layout

A Short Summary of Javali

CSC Java Programming, Fall Java Data Types and Control Constructs

CS121/IS223. Object Reference Variables. Dr Olly Gotel

Special Topics: Programming Languages

PIC 20A Number, Autoboxing, and Unboxing

C++ for Java Programmers

School of Computer Science CPS109 Course Notes Set 7 Alexander Ferworn Updated Fall 15 CPS109 Course Notes 7

VARIABLES AND TYPES CITS1001

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Lecture Notes on Arrays

Java Threads and intrinsic locks

CPSC 3740 Programming Languages University of Lethbridge. Data Types

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

1.00 Lecture 4. Promotion

Design Patterns: State, Bridge, Visitor

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Last Class. While loops Infinite loops Loop counters Iterations

Programming II (CS300)

Computer Science 1 Ah

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

Exercise 4: Loops, Arrays and Files

6.001 Notes: Section 15.1

About this exam review

Compaq Interview Questions And Answers

TOPICS TO COVER:-- Array declaration and use.

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

More on Objects in JAVA TM

Inheritance and Interfaces

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

3.1 Class Declaration

ISY00245 Principles of Programming. Module 7

Programming II (CS300)

9 Working with the Java Class Library

Exam 2. CSC 121 MW Class. Lecturer: Howard Rosenthal. April 26, 2017

Pace University. Fundamental Concepts of CS121 1

G Programming Languages - Fall 2012

Goals of this Lecture

CHAPTER 7 ARRAYS: SETS OF SIMILAR DATA ITEMS

(Refer Slide Time: 06:01)

int a; int b = 3; for (a = 0; a < 8 b < 20; a++) {a = a + b; b = b + a;}

Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters

Exam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

The Sun s Java Certification and its Possible Role in the Joint Teaching Material

Answer Key. 1. General Understanding (10 points) think before you decide.

CHAPTER 5 VARIABLES AND OTHER BASIC ELEMENTS IN JAVA PROGRAMS

Array. Array Declaration:

Language Features. 1. The primitive types int, double, and boolean are part of the AP

CS558 Programming Languages

CSE 142 Su 04 Computer Programming 1 - Java. Objects

Introduction Unit 4: Input, output and exceptions

1007 Imperative Programming Part II

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Chapter 6. Arrays. Array Basics Arrays in Classes and Methods Programming with Arrays and Classes Sorting Arrays Multidimensional Arrays

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #34. Function with pointer Argument

Arrays and ArrayLists. Ananda Gunawardena

Object-Oriented Programming for Scientific Computing

Chapter 12: Pointers and Arrays. Chapter 12. Pointers and Arrays. Copyright 2008 W. W. Norton & Company. All rights reserved.

Exception-Handling Overview

Points To Remember for SCJP

CSCI 355 Lab #2 Spring 2007

Summer Final Exam Review Session August 5, 2009

Goal. Generic Programming and Inner classes. Minor rewrite of linear search. Obvious linear search code. Intuitive idea of generic linear search

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

Intermediate Code Generation

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Object Oriented Programming

M/s. Managing distributed workloads. Language Reference Manual. Miranda Li (mjl2206) Benjamin Hanser (bwh2124) Mengdi Lin (ml3567)

C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism

COMP-202: Foundations of Programming. Lecture 26: Image Manipulation; Wrap-Up Jackie Cheung, Winter 2015

Nested Loops. A loop can be nested inside another loop.

APCS Semester #1 Final Exam Practice Problems

ADTs, Arrays, Linked Lists

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

Programming for Electrical and Computer Engineers. Pointers and Arrays

Computer Science 1 Bh

Computer Science is...

6.001 Notes: Section 17.5

Operators and Expressions

Arrays. Chapter Arrays What is an Array?

Transcription:

Topics Data Structures and Information Systems Part 1: Data Structures Michele Zito Lecture 3: Arrays (1) Data structure definition: arrays. Java arrays creation access Primitive types and reference types Internal representation of Java arrays and potential pitfalls.. p.1/74. p.2/74 Definition Java arrays An array is a sequence of components (of the same type) with the following properties the length of the array equals the number of components of the array and is fixed when the array is created each component of the array has a fixed and unique index the indices range from a lower index bound to an upper index bound each 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 Java arrays have the following specific properties: For an array of length n, the lower index bound is always 0 and 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 its components is the same However, if all components are of type T, where T is an object class, then it can store objects of any subclass of T The notation for accessing the component of an array a at index i is a[i]. p.3/74. p.4/74

Java arrays: Creation (1) Java arrays: Creation (2) The three steps for creating an array are: 1. Defining an array There are two ways to declare that a variable is an array i n t [ ] Array1 ; i n t Array2 [ ] ; both have exactly the same effect The 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. The three steps for creating an array are: 3. Initialising the components of the array If we do not specify the initial values for the components of an array, then the components are initialised with 0 or null as applicable, but it is good practise not to rely on this feature of Java. One way of initialising an array yourself is by specifying the initial 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 size of the array. It will automatically be inferred that Array2 has 4 components with indices 0 to 3.. p.5/74. p.6/74 Java arrays: Creation (3) Java arrays: Creation (4) The first two steps of creating an array can be performed as one: 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 also be merged with the others: i n t [ ] Array5 = { 1, 2 } ; i n t Array6 [ ] = { 6, 5, 4 } ; In all the examples up to now we have used an integer constant as the size of the array, but this is not necessary: import java. i o. ; cl a ss 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 void main ( S t r i n g args [ ] ) throws IOException { } } System. out. p r i n t l n ( " Enter size of array : " ) ; i n t n = new I n t e g e r ( keyboardinput. readline ( ) ). i n t V a l u e ( ) ; i n t [ ] Array1 = new i n t [ n ] ; System. out. p r i n t l n ( " Length of Array1 : " + Array1. length ) ;. p.7/74. p.8/74

Java arrays: Creation (5) Here is a transcript of a run of TestArray: Enter size of array : 2 Length of Array1 : 2 The example also illustrates that arrays are allocated dynamically 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 size of array : 0 Length of Array1 : 0 However, an array of size 0 has no components. So, we cannot store anything in it. Java arrays: Creation (6) What happens if we try to create an array of size -1? Enter size of array : 1 Exception i n thread " main " java. lang. NegativeArraySizeException at TestArray3. main ( TestArray3. java : 1 2 ) This leads to a run-time error that causes an exception to be thrown Would it make a difference if we could already see in the program 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 is wrong. We still get the same run-time error. p.9/74. p.10/74 Exceptions Java arrays: Access (1) An exception is an event that occurs during program execution and which makes further execution impossible Standard examples are divide by zero error and arithmetic overflow, but there are many more An exception handler is a piece of code that gets invoked when an exception is encountered It allows the program to either fix what ever caused the exception, or abort execution gracefully The default exception handler just outputs an error message and terminates the program execution How you write your own exception handlers will be a subject of COMP 213 One of the standard operations performed on arrays is to loop through all array elements to apply some operation to each 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 the number of components of Array2 would require us to change the for-loop But this can easily be avoided using the length attribute of arrays f o r ( i n t i = 0 ; i <Array2. l e n g th ; i + + ) { System. out. p r i n t l n ( Array2 [ i ] ) ; }. p.11/74. p.12/74

Java arrays: Access (2) Always remember that in a Java array of size n, indices range from 0 to n 1 and not from 1 to n Executing the following program i n t [ ] Array2 = { 2, 3, 5, 7 } ; f o r ( i n t i = 1 ; i < = 4; i + + ) { System. out. p r i n t l n ( Array2 [ i ] ) ; } results in the following output 3 5 7 Exception i n thread " main " java. lang. ArrayIndexOutOfBoundsException : 4 at TestArray. main ( TestArray. java : 8 ) Java arrays: Access (3) Would it make any difference if we could already see in the program code that an illegal array access is tried? i n t [ ] Array2 = { 2, 3, 5, 7 } ; System. out. p r i n t l n ( Array2 [ 4 ] ) ; No! The Java compiler will again not indicate that something is wrong. We still get the same run-time error Exception i n thread " main " java. lang. ArrayIndexOutOfBoundsException : 4 at TestArray. main ( TestArray. java : 8 ). p.13/74. p.14/74 The Array Data Structure and Java array We can see that Java arrays provide all the operations of the Array data structure However, there are number of additional operations that we might want to perform on arrays: E.g. given an array a and a data item d we can define the index of d in a as the smallest index i such that a[i] equals d (the index of d in a is undefined if d is not stored in a) So, in a 2 3 5 7 3 0 1 2 3 4 the index of 3 is 1, the index of 7 is 3, etc. Primitive types and reference types (1) Remember that Java distinguishes between primitive (data) types and reference types The primitive types are: Type Default value integer: byte, short, int, long 0 floating point: float, double +0.0f or +0.0d character: char null character logical: boolean false others: void A variable of a primitive type is directly associated with a memory location storing the value of the variable If a variable is not initialised explicitly, then the default value for its type is used to initialise it implicitly. p.15/74. p.16/74

Primitive types and reference types (2) Instead of talking about memory locations we often depict this situation as follows: For primitive types, variable value var1 == var2 is true if the stored values for variables var1 and var2 are identical 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 a memory location that stores a value Instead it is associated with a memory location that stores the 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.17/74. p.18/74 Primitive types and reference types (4) Instead of talking about memory locations and addresses we often depict this situation as follows: variable value(s) The declaration of a reference variable does not initialise the variable with the address of some value(s) Instead, the variable is given the special value null if it is an instance or class variable variable null... 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 it compares the value found at the addresses stored in var1 and var2 However, by default, it returns the same result as var1 == var2 (given that var1 is non-null). p.19/74. 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 components are of type T and allocates memory space for n such components a T[] n class tag length 0 1 n 2 n 1 Equality between array variables A consequence of the fact that Java arrays are reference types is that the == operator compares references not the data 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 the data stored in arrays either So, in our example Array1.equals(Array2) again evaluates to false. p.21/74. p.22/74 Assignments Another consequence of the fact that Java arrays are reference types is that an assignment statement like Array1 = Array2 copies the address stored in Array2 to Array1, making both Array1 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 Data Structures and Information Systems Part 1: Data Structures Michele Zito Lecture 4: Arrays (2) Array1 [ 4 ] = 1 3. p.23/74. p.24/74

Topics Internal representation of Java arrays Java arrays: Access implementation Arrays: Advantages and disadvantages Enlarging arrays Arrays of reference types Arrays of string objects Arrays of objects Java arrays are reference types Example: T [ ] a = new T [ n ] Defines an array variable with name a whose components are of type T and allocates memory space for n such components a T[] n class tag length 0 1 n 2 n 1. p.25/74. p.26/74 Java arrays: Access implementation a T[] n class tag length 0 1 n 2 n 1 Given an index i how do we work out where to look for the component a[i]? Arrays: Advantages and disadvantages Arrays, including Java arrays, are static data structures since the number of elements they can store is fixed at the time of creation As such they inherit all the advantages and disadvantages of static data structures 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 that it takes an amount of time that is independent of the size of the array).. p.27/74. p.28/74

Arrays: Advantages Arrays: Disadvantages Easy to specify (declaration, allocation of memory space, initialisation can all be 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, for example, in linked lists, due to contiguous storage (good locality) and constant time computation of the address of a component A potential disadvantage of arrays (depending on the application) is the need to know the size at the time of allocation. Careful design is required to make sure that the array will be large enough to hold the largest possible group of data but no 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 transferred across.. p.29/74. p.30/74 Enlarging arrays Arrays as method arguments (1) Assume that oldarray is an integer array which is too small for the number of elements we want to store in it The following code replaces oldarray by an array of twice the size of the original array i n t oldsize = oldarray. length ; i n t newsize = 2 oldarray. length ; i n t [ ] newarray = new i n t [ newsize ] ; f o r ( i n t i = 0 ; i < oldarray. length ; i ++) newarray [ i ]= oldarray [ i ] ; oldarray = newarray ; oldarray [ oldsize ] = 5 ; Here is an example of how to write a method that takes an array as an argument It simply encapsulates the algorithm for enlarging an array we have just seen in a method p u b l i c s t a t i c i n t [ ] doublesize ( i n t [ ] oldarray ) { } i n t [ ] newarray = new i n t [ 2 oldarray. length ] ; f o r ( i n t i = 0 ; i < oldarray. length ; i ++) newarray [ i ] = oldarray [ i ] ; r e t u r n ( newarray ) ; The last line works now (instead of throwing an exception). p.31/74. p.32/74

Arrays as method arguments (2) Arrays as method arguments (3) Now we use this method in a program: import java. i o. ; cl a ss TestArray5 { p u b l i c s t a t i c i n t [ ] doublesize ( i n t [ ] oldarray ) {... } p u b l i c s t a t i c void main ( S t r i n g args [ ] ) { i n t [ ] primes = { 2, 3, 5 } ; i n t oldsize = primes. length ; primes = doublesize ( primes ) ; primes [ oldsize ] = 7 ; f o r ( i n t i = 0 ; i <primes. length ; i ++) System. out. p r i n t l n ( primes [ i ] ) ; } }. p.33/74 The output of program TestArray5 is: 2 3 5 7 0 0 Thus, it seems that instead of three integers, our array is now able to store six integers Doesn t that mean that what we said about the disadvantages of static data structures, and Java arrays in particular, is wrong?. p.34/74 Static data structures again Arrays of reference types Static data structures, including Java arrays, are fixed in size at the time of creation The method doublesize seems to allow us to enlarge a Java array However, looking closer, doublesize does not enlarge the array it is given as an argument, but it creates a completely new array Also, using doublesize we now incur the same disadvantage that dynamic data structures have: a memory allocation overhead As a consequence, this approach only makes sense, if the number of times we have to use doublesize is significantly smaller than the number of times we have to access array components (so, that we are still faster than with a dynamic data structure). p.35/74 Apart from arrays of primitive data types we can have arrays of reference types (objects) These arrays of reference types are created and used in much the same way as the arrays we have already seen Note that in an array of reference types not the objects are stored in the array, but references (memory locations) to the objects The objects themselves have to be created and memory space has to be allocated for them separately. p.36/74

Arrays of string objects: Creation Arrays of string objects: Storing strings 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 memory space for the strings, it only allocates space for an array storing four memory locations (of strings) Also, all the components are initialised with the null reference, not with an empty string Next, let us store strings in our array of strings words [ 1 ] = " tim " ; words [ 2 ] = " tom " ; words [ 3 ] = " tim " ; Remember, "tim" and "tom" are so-called string literals Are words[1] and words[3] equal? Both as well as words[1] == words[3] words[1].equals(words[3]) return true! This is due to the compiler which only creates one internal string object for both occurrences of "tim" in our code. p.37/74. p.38/74 Arrays of objects: Creation Arrays of objects: Storing objects The most general kind of array would have components of type Object The Object class is located at the top of the Java class hierarchy Every Java class is a descendant, direct or indirect, of the Object class, but not the primitive data types We can declare an array with components of type Object as follows: Object [ ] objarray = new Object [ 3 ] ; In the components of objarray we can now store objects of any subclass of Object objarray [ 0 ] = " tim " ; objarray [ 1 ] = new BasicBox ( 1, 2, 3 ) ; Remember that BasicBox is a class that we have defined earlier We assume that the definition of the BasicBox class is extended 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 + ", " + height + ", " + width + " ) " ) ; which overrides the default method for providing a String representation of an object. p.39/74. p.40/74

Arrays of objects: Storing primitive data Arrays of objects: Storing primitive data But, unfortunately, we cannot directly store an element of a primitive data type in it Including the following code objarray [ 2 ] = 5 ; into our program results in the following error message by the compiler: TestObjectArray. java : 1 2 : incompatible types found : i n t required : java. lang. Object objarray [ 2 ] = 5 ; ^ 1 e r r o r To store an integer value like 5 in objarray we have to make use of a wrapper class Each of the primitive data types like char or int has a corresponding wrapper class associated with it, named Character, Integer, etc. Each of these classes wraps a primitive data type into a class which in turn is a subclass of Object So, objarray [ 2 ] = new I n t e g e r ( 5 ) ; wraps the number 5 into an object of class Integer, which can be assigned to a component of objarray. p.41/74. p.42/74 Arrays of objects: Accessing (1) Arrays of objects: Accessing (2) To access all the components of an array of reference types we can use the same code that we have used for integer arrays f o r ( i n t i = 0 ; i < objarray. length ; i ++) System. out. p r i n t l n ( " objarray [ " + i + " ] = " + objarray [ i ] ) ; will produce the following output objarray [ 0 ] = tim objarray [ 1 ] = box ( 1, 2, 3 ) objarray [ 2 ] = 5 objarray [ 3 ] = n u l l objarray [ 4 ] = n u l l However, since we have now turned an integer value into an Integer object, we can no longer use it in the same way as before Adding the line i n t n = 3 + objarray [ 2 ] ; to our program results in the following error message by the compiler: TestObjectArray. java : 1 6 : operator + cannot be applied to 1 e r r o r i n t n = 3 + objarray [ 2 ] ; ^ i n t, java. lang. Object. p.43/74. p.44/74

Arrays of objects: Accessing (3) Arrays of objects: Accessing (4) Instead, we have to unwrap the Integer object first, to get the integer value back Unfortunately, the straightforward approach i n t n = 3+ objarray [ 2 ]. i n t V a l u e ( ) ; produces again an error message by the compiler: TestObjectArray. java : 1 7 : cannot resolve symbol symbol : method i n t V a l u e ( ) l o c a t i o n : class java. lang. Object i n t n = 3 + objarray [ 2 ]. i n t V a l u e ( ) ; One way of solving this problem is to use typecasting: We typecast objarray[2] from the Object class to its subclass Integer Once this is done, we can use the intvalue method of the Integer class to retrieve the actual integer value i n t n = 3 + ( ( I n t e g e r ) objarray [ 2 ] ). i n t V a l u e ( ) ; System. out. p r i n t l n ( " n = " + n ) ; produces the output n = 8 The compiler only knows that the components of objarray belong to class Object It does not know that objarray[2] belongs to Integer. p.45/74. p.46/74 Topics Data Structures and Information Systems Part 1: Data Structures Michele Zito Lecture 5: Multi-dimensional arrays Multi-dimensional arrays: Examples of applications Multi-dimensional array, definition 2-dimensional arrays in Java Access implementation Creation Cloning Access 2-dimensional arrays as method arguments Higher-dimensional arrays in Java Example: Train departure information. p.47/74. p.48/74

(Linear) Arrays 2-D organisation: Examples (1) 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 table form instead of a linear list: timetable chess board distances between cities theatre seating layout 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. p.49/74 S E T D E S P A I R E D. p.50/74 2-D organisation: Examples (2) 3-D organisation: Examples Images rows of columns of pixels (picture elements) each pixel has a value binary images: black - 0, white - 1 greyscale: from black to white - 0..255 each pixel is identifiable by its 2-D coordinates (row number and column number) 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 red value of each pixel in its components, the other two arrays do the same for the green and blue value) or one two-dimensional array where each component is a one-dimensional array (storing the red, green, and blue value of a single pixel). p.51/74. p.52/74

Multi-dimensional array A multi-dimensional array is a collection of components indexed by unique integer sequences of fixed length with the following properties: the length of an index sequence is the rank or number of dimensions of a multi-dimensional array for each dimension d there is a lower index bound l d and a higher index bound h d for an array of dimension n, an index is an integer sequence written [i 1 ]...[i n ] such that for every dimension d, l d i d h d any 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 l 2 l 2 +1... h 2 1 h 2 l 1 a[l 1 ][l 2 ] a[l 1 ][h 2 ] l 1 +1. h 1 1 h 1 a[h 1 ][l 2 ] a[h 1 ][h 2 ] 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 Java Java does not actually support 2-dimensional (or higher dimensional) arrays as such We can achieve the same effect, though, using a 1-dimensional array whose components are 1-dimensional arrays i n t [ ] [ ] a = new i n t [ 3 ] [ 4 ] a class tag length 0 1 2 class tag length 0 1 2 3 a[0] is a 1-dimensional array a[0][0]is an integer component Access implementation (1) How does Java find the memory location of a component a[i][j] in a 2-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) of the 1-dimensional array storing a[i][j]. p.55/74. p.56/74

Access implementation (2) Access implementation: Properties How does Java find the memory location of a component a[i][j] of a 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) This algorithm can easily be generalised to arrays of arbitrary dimensionality For example, for a 3-dimensional array we have to perform 5 steps 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 need a[i][j][k]. Note that if a[i][j] is of reference type, then the size of a component is again the size of an address. p.57/74. p.58/74 2-dimensional arrays in Java: Creation (1 2-dimensional arrays in Java: Creation (2 Just as for 1-dimensional arrays, the three steps for creating a 2-dimensional array are: (1) Defining an array, (2) Allocating memory space for an array, and (3) Initialising an array 1. Defining a 2-dimensional array There are two ways to declare that a variable is a 2-dimensional array i n t [ ] [ ] Array1 ; i n t Array2 [ ] [ ] ; both have exactly the same effect The declaration itself does not allocate memory 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-dimensional array with four components of type int Alternatively, we can view Array1 as a 2-dimensional array 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 of the true internal structure of 2-dimensional arrays in Java. p.59/74. p.60/74

2-dimensional arrays in Java: Creation (3 2-dimensional arrays in Java: Creation (4 3. Initialising the components of a 2-dimensional array Unless we specify initial values for the components of a 2-dimensional array ourselves, then the component are initialised 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 type String which are initialised to null, not to the empty string One way of initialising an array ourselves is by specifying the 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.61/74. p.62/74 2-dimensional arrays in Java: Creation (5 2-dimensional arrays in Java: Creation (6 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 Array4 and Array5 in Array2[0] and Array2[1], respectively Instead it stores references to the already existing Array4 and Array5 in Array2[0] and Array2[1], respectively Consequently, if we change, for example, Array4[1], we also 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-dimensional arrays, 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.63/74. p.64/74

2-dimensional arrays in Java: Cloning Be careful: It is possible to clone multi-dimensional arrays as well, but the clone is shallow Remember that multi-dimensional arrays in Java are arrays of 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 that stores the memory locations m 0 and m 1 of two 1-dimensional arrays If we clone Array2, then we only create a new 1-dimensional array that again stores m 0 and m 1 2-dimensional arrays in Java: Access (1) While we have used a single for-loop to access all the components of an 1-dimensional array, we can use two nested for-loops to do the same for a 2-dimensional array: f o r ( i n t i = 0 ; i < Array2. length ; i + + ) { } f o r ( i n t j = 0 ; j < Array2 [ i ]. length ; j ++) System. out. p r i n t ( " Array2 [ " + i + " ] [ " + j + " ] = " System. out. p r i n t ( " \ n " ) ; prints out + Array2 [ i ] [ j ] + ", " ) ; 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.65/74. p.66/74 2-dimensional arrays in Java: Access (2) 2-dimensional arrays as method argument f o r ( i n t i = 0 ; i < Array2. length ; i + + ) { } f o r ( i n t j = 0 ; j < Array2 [ i ]. length ; j ++) System. out. p r i n t ( " Array2 [ " + i + " ] [ " + j + " ] = " System. out. p r i n t ( " \ n " ) ; + Array2 [ i ] [ j ] + ", " ) ; Note that we use Array2.length to determine the number of rows of Array2 in the outer for-loop And we use Array2[i].length to determine the number of columns of the 1-dimensional array stored in Array2[i] in the inner for-loop Note also, the use of i in Array2[i].length means that there is no easy way to swap the two loops Initialising the component with index [i][j] in a 2-dimensional array with (i+1)*(j+1) In Java this is a trivial exercise: p u b l i c s t a t i c void i n i t A r r a y ( i n t Array [ ] [ ] ) { f o r ( i n t i = 0 ; i < Array. l e n g th ; i ++) f o r ( i n t j = 0 ; j < Array [ i ]. l e n g th ; j ++) Array [ i ] [ j ] = ( i +1) ( j + 1 ) ; } This method works since Any argument will be passed to this method using call-by-reference Java will only compute at run-time what the memory location of Array[i][j] is. p.67/74. p.68/74

Higher-dimensional arrays in Java Example: Train departure information Java permits arrays of three, four or more dimensions The way these arrays are created is a straightforward generalisation of the way 2-dimensional arrays are created Here is an example of the creation of a 3-dimensional array: class F i l l 3 D A r r a y { p u b l i c s t a t i c void main ( S t r i n g args [ ] ) { i n t [ ] [ ] [ ] M = new i n t [ 3 ] [ 4 ] [ 2 ] ; We want to develop a very simple information system for train 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 } } f o r ( i n t row = 0 ; row < M. length ; row++) f o r ( i n t c o l = 0 ; c o l < M[ row ]. length ; c o l ++) f o r ( i n t ver = 0 ; ver < M[ row ] [ c o l ]. length ; ver ++) M[ row ] [ c o l ] [ ver ] = row+ c o l +ver ; The only kind of query we deal with is When and where does the next train to X leave?. p.69/74. p.70/74 Train departure information: The code (1 Train departure information: The code (2 import java. i o. ; class 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. length ; 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 p u b l i c s t a t i c void main ( S t r i n g args [ ] ) throws IOException { InputStreamReader i n p u t = new InputStreamReader ( System. i n ) ; BufferedReader keyboardinput = new BufferedReader ( i n p u 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 " ) ; else System. out. p r i n t l n ( i n f o [ 0 ] + " departing at t r a c k " + i n f o [ 1 ] ) ; } }. p.72/74

Train departure information: Script Here are two runs of the program: Information successfully retrieved Where do you want to go? Leeds 9:15 departing at track 10 No information found Where do you want to go? York Sorry, no train to this destination. p.73/74