Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Multidimensional Arrays l Vectors Multidimensional Arrays.

Slides:



Advertisements
Similar presentations
Slides prepared by Rose Williams, Binghamton University Chapter 14 Generics and the ArrayList Class.
Advertisements

JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
HST 952 Computing for Biomedical Scientists Lecture 8.
Chapter 101 Dynamic Data Structures and Generics Chapter 10.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming.
1 Chapter 10 l Vector l Linked Data Structures l interface Dynamic Data Structures.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
Slides prepared by Rose Williams, Binghamton University Chapter 14 Generics and the ArrayList Class.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 10 *Arrays with more than one dimension *Java Collections API.
C++ for Engineers and Scientists Third Edition
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
Chapter 9 Introduction to Arrays
Chapter 10Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Announcements/Reminders l Project 6 due on Thursday March 31 l Exam.
Arrays Chapter 6 Array Basics Arrays in Classes and Methods
Chapter 10 2D Arrays Collection Classes. Topics Arrays with more than one dimension Java Collections API ArrayList Map.
11 Chapter 8 ARRAYS Continued. 22 MULTI-DIMENSIONAL ARRAYS A one-dimensional array is useful for storing/processing a list of values. For example: –The.
Java Unit 9: Arrays Declaring and Processing Arrays.
Chapter 10Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 10 l Vectors l Linked Data Structures Dynamic Data Structures.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Chapter 10Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 10 l Array Basics l Arrays in Classes and Methods l Programming.
1 Week 9 l Array Basics l Arrays in Classes and Methods l Programming with Arrays and Classes l Sorting Arrays l Multidimensional Arrays Arrays.
Lecturer: Dr. AJ Bieszczad Chapter 6 COMP 150: Introduction to Object-Oriented Programming 6-1 l Array Basics l Arrays in Classes and Methods l Programming.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming.
1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming with Arrays and Classes l Sorting Arrays l Multidimensional Arrays Arrays.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming.
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
ArrayList, Multidimensional Arrays
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 9 Arrays.
Chapter 10. Arrays Array Basics Arrays in Classes and Methods Programming with Arrays and Classes Sorting Arrays Computer Programming with JAVA.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
ARRAYS Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
Chapter 11. Multidimensional Arrays and Vectors Multidimensional Arrays Vectors Computer Programming with JAVA.
Chapter overview This chapter focuses on Array declaration and use Bounds checking and capacity Arrays storing object references Variable length parameter.
Dynamic Data Structures and Generics Chapter 10. Outline Vectors Linked Data Structures Introduction to Generics.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Static arrays.
Lecturer: Dr. AJ Bieszczad Chapter 10 COMP 150: Introduction to Object-Oriented Programming 10-1 l Vectors l Linked Data Structures Dynamic Data Structures.
CMSC 202 Arrays 2 nd Lecture. Aug 6, Array Parameters Both array indexed variables and entire arrays can be used as arguments to methods –An indexed.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Chapter 6 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays and Classes l Sorting Arrays l Multidimensional Arrays ** ** multidimensional.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
CSE 1201 Object Oriented Programming ArrayList 1.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
Chapter 10Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 10 l Vectors l Linked Data Structures Dynamic Data Structures.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 8: Part 3 Collections and Two-dimensional arrays.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
C++ Array 1. C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Chapter 9 Introduction to Arrays Fundamentals of Java.
KUKUM-06/07 EKT120: Computer Programming 1 Week 6 Arrays-Part 1.
Chapter 10Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 10 l Vectors l Linked Data Structures Dynamic Data Structures.
Arrays Chapter 7.
EKT472: Object Oriented Programming
Arrays Chapter 6 Array Basics Arrays in Classes and Methods
Vectors Linked Data Structures
Can store many of the same kind of data together
Dynamic Data Structures and Generics
Arrays.
Presentation transcript:

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Multidimensional Arrays l Vectors Multidimensional Arrays and Vectors

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 2 Overview l This chapter is a continuation of the previous one l If one-dimensional arrays are good, multi-dimensional arrays must be better l Vectors: arrays reconfigured as a class type

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 3 Multidimensional arrays l Arrays with more than one index »number of dimensions = number of indexes l Arrays with more than two dimensions are a simple extension of two-dimensional (2-D) arrays l A 2-D array corresponds to a table or grid »one dimension is the row »the other dimension is the column »cell: an intersection of a row and column »an array element corresponds to a cell in the table

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 4 Table as a 2-D array l The table assumes a starting balance of $1000 l First dimension: row identifier - Year l Second dimension: column identifier - percentage l Cell contains balance for the year (row) and percentage (column) l Balance for year 4, rate 7.00% = $1311 Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 4

Table as a 2-D array l Generalizing to two indexes: [row][column] l First dimension: row index l Second dimension: column index l Cell contains balance for the year/row and percentage/column l All indexes use zero-numbering »Balance[3][4] = cell in 4th row (year = 4) and 5th column (7.50%) »Balance[3][4] = $1311 (shown in yellow) Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 5 Row Index 3 (4th row) Column Index 4 (5th column)

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 6 Java code to create a 2-D array l Syntax for 2-D arrays is similar to 1-D arrays Declare a 2-D array of int s named table »the table should have ten rows and six columns int[][] table = new int[10][6];

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 7 Method to calculate the cell values Each array element corresponds to the balance for a specific number of years and a specific interest rate (assuming a starting balance of $1000): balance(starting, years, rate) = (starting) x (1 + rate) years The repeated multiplication by (1 + rate) can be done in a for loop that repeats years times. balance method in class InterestTable (excerpt from Display 11.3/page 607):

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 8 Processing a 2-D array: for loops nested 2-deep Arrays and for loops are a natural fit To process all elements of an n -D array nest n for loops »each loop has its own counter that corresponds to an index l For example: calculate and enter balances in the interest table »inner loop repeats 6 times (six rates) for every outer loop iteration »the outer loop repeats 10 times (10 different values of years ) »so the inner repeats 10 x 6 = 60 times = # cells in table Excerpt from main method of InterestTable (Display 11.3/page 607):

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 9 Multidimensional array parameters and returned values l Methods may have multi-D array parameters l Methods may return a multi-D array as the value returned l The situation is similar to 1-D arrays, but with more brackets Example: a 2-D int array as a method argument showTable method from class InterestTable2 (Display 11.5/page 614): Notice how the number of columns is obtained Notice how the number of rows is obtained

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 10 Ragged arrays l Ragged arrays have rows of unequal length »each row has a different number of columns, or entries l Ragged arrays are allowed in Java Example: create a 2-D int array named b with 5 elements in the first row, 7 in the second row, and 4 in the third row: int[][] b; b = new int[3][]; b[0] = new int[5]; b[1] = new int[7]; b[2] = new int[4];

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 11 Vectors "Well, I'll eat it," said Alice, "and if it makes me grow larger, I can reach the key; and if it makes me grow smaller, I can creep under the door; so either way I'll get into the garden…" Lewis Carroll, Alice's Adventures in Wonderland VECTORS Think of them as arrays that can get larger or smaller when a program is running.

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 12 Arrays versus Vectors Arrays Bad: l Size is fixed when declared l Inefficient storage: can use a partially full array, but space has been allocated for the full size l If one more value needs to be added past the maximum size the array needs to be redeclared Good: l More efficient (faster) execution l Allows primitive type elements Vectors Good : l Size is not fixed l Better storage efficiency: a partially full vector may be allocated just the space it needs l If one more value needs to be added past the maximum size the vector size increases automatically Bad: l Less efficient (slower) execution l Elements must be class types (primitive types not allowed)

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 13 Using vectors l Vectors are not automatically part of Java »they are in the util library »you must import java.util.* Create a vector with an initial size of 20 elements: Vector v = new Vector(20);

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 14 Initial capacity and efficiency: a classic engineering tradeoff l Engineering involves making difficult tradeoffs »"There's no such thing as a free lunch." –an American saying »Usually, if you gain something you lose something somewhere else l Choosing the initial size of a vector is an example of a tradeoff »making it too large wastes allocated memory space »making it too small slows execution –it takes time to resize vectors dynamically l Solution? »optimize one at the expense of the other »or make good compromises –choose a size that is not too big and not too small

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 15 Vector syntax l The idea is the same as for arrays, but the syntax is different l As with arrays, the index must be in the range 0 to size-of-the-vector Array: a is a String array a[i] = "Hi, Mom!"); String temp = a[i]; Vector: v is a vector v.setElementAt("Hi, Mom!", i); String temp = (String)v.elementAt(i); Instead of the index in brackets and = for assignment, use vector method setElementAt with two arguments, the value and the index Use vector method elementAt(int index) to retrieve the value of an element Note: the cast to String is required because the base type of vector elements is Object

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 16 Vector methods l The vector class includes many useful methods: »constructors »array-like methods, e.g. setElementAt & elementAt »methods to add elements »methods to remove elements »search methods »methods to work with the vector's size and capacity, e.g. to find its size and check if it is empty »a clone method to copy a vector l See Display 11.8/pages 624-6

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 17 A little detail about setElementAt "The devil's in the details." –an American engineering saying l Vectors put values in successive indexes »addElement is used to put initial values in a vector »new values can be added only at the next higher index You cannot use setElemetAt to put a value at any index »setElemetAt can be used to assign the value of an indexed variable only if it has been previously assigned a value with addElement

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 18 Base type of vectors l The base type of an array is specified when the array is declared »all elements of arrays must be of the same type The base type of a vector is Object »elements of a vector can be of any class type »in fact, elements of a vector can be of different class types! »to store primitive types in a vector they must be converted to a corresponding wrapper class Good Programming Practice Although vectors allow elements in the same vector to be of different class types, it is best not to have a mix of classes in the same vector - –it is best to have all elements in a vector be the same class type.

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 19 Detail: one consequence of the base type of vectors being Object The following code looks very reasonable but will produce an error saying that the class Object does not have a method named length : Vector v = new Vector() String greeting = "Hi, Mom!"; v.addElement(greeting); System.out.println("Length is " + (v.elementAt(0)).length()); String, of course, does have a length method, but Java sees the type of v.elementAt(0) as Object, not String Solution? Cast v.elementAt(0) to String : System.out.println ("Length is " + (String)(v.elementAt(0)).length());

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 20 One more detail: size versus capacity l Be sure to understand the difference between capacity and size of a vector: »capacity is the declared size of the vector –the current maximum number of elements »size is the actual number of elements being used –the number of elements that contain valid values, not garbage –remember that vectors add values only in successive indexes Loops that read vector elements should be limited by the value of size, not capacity, to avoid reading garbage values

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 21 Programming tip: increasing storage efficiency of vectors l A vector automatically increases its size if elements beyond its current capacity are added l But a vector does not automatically decrease its size if elements are deleted The method trimSize shrinks the capacity of a vector to its current size so there is no extra, wasted space »the allocated space is reduced to whatever is currently being used To use storage more efficiently, use trimSize when a vector will not need its extra capacity later

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 22 And another detail: correcting the return type of clone The method clone is used to make a copy of a vector but its return type is Object, not Vector »of course you want it be Vector, not Object l So, what do you do? »Cast it to Vector Vector v = new Vector(10); Vector otherV; otherV = vector; Vector otherV = (Vector)v.clone(); This just makes otherV another name for the vector v (there is only one copy of the vector and it now has two names) This creates a second copy of v with a different name, otherV

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 23 And yet another detail: protecting private variables l Just as with arrays, be careful not to return addresses of private vector variables, otherwise calling methods can access them directly »"Information Hiding" is compromised l To protect against it, return a copy of the vector »use clone as described in the previous slide l But that's not all: »if the elements of the vector are class (and not primitive) types, they may not have been written to pass a copy »they may pass the address »so additional work may be required to fix the accessor methods

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 24 Summary l Arrays can have more than one index. l Each index is called a dimension. l Hence, multidimensional arrays have multiple indexes, »e.g. an array with two indexes is a two-dimensional array. l A two-dimensional array can be thought of as a grid or table with rows and columns: »one index is for the row, the other for the column. l Multidimensional arrays in Java are implemented as arrays of arrays, »e.g. a two-dimensional array is a one-dimensional array of one- dimensional arrays. l Vectors can be thought of as arrays that can grow in length as needed during run time. The base type of all vectors is Object. l Thus, vector elements can be of any class type, but not primitive types.