Chapter 6: Arrays and Vectors. 2 Arrays and Vectors  Arrays and vectors are objects that help us organize large amounts of information  Chapter 6 focuses.

Slides:



Advertisements
Similar presentations
Arrays. What is an array An array is used to store a collection of data It is a collection of variables of the same type.
Advertisements

CSCI 1100/ , 6.2, 6.4 April 12, 15, 17.
Lecture 6 b Last time: array declaration and instantiationarray declaration and instantiation array referencearray reference bounds checkingbounds checking.
Chapter 6: Arrays Java Software Solutions for AP* Computer Science
Arrays.
1 (c) elsaddik CSI 1102 Introduction to Software Design Prof. Dr.-Ing. Abdulmotaleb El Saddik University of Ottawa (SITE.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
8. Arrays 8.1 Using Arrays 8.2 Reference versus Value Again 8.3 Passing Array Arguments and Returning Arrays 8.4 An Example: Simulating Rolls of the Dice.
Arrays Clark Savage Turner, J.D., Ph.D. Copyright © 2000 by C Scheftic. All rights reserved. These notes do rely heavily.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
1 More on Arrays Passing arrays to or from methods Arrays of objects Command line arguments Variable length parameter lists Two dimensional arrays Reading.
1 Arrays b An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
Wecksten, Mattias Arrays Based on templates from Lewis & Loftus.
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.
Aalborg Media Lab 28-Jun-15 Software Design Lecture 8 “Arrays”
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
Arrays in Java Selim Aksoy Bilkent University Department of Computer Engineering
Chapter 6: Arrays Java Software Solutions Third Edition
Unit 5 1 Arrays and Vectors H Arrays and vectors are objects that help us organize large amounts of information H We will talk about: array declaration.
© 2011 Pearson Education, publishing as Addison-Wesley 1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 6 focuses.
Arrays Chapter 7 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 6 focuses on: array declaration and use passing arrays and array.
1 7 Arrays. 2 Arrays are objects that help us organize large amounts of information Chapter 7 focuses on: –array declaration and use –bounds checking.
7. Arrays. Topics Declaring and Using Arrays Some Array Algorithms Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
1 Dr. Seuss again: "Too Many Daves"  Did I ever tell you that Mrs. McCave Had twenty-three sons, and she named them all Dave?  Well, she did. And that.
Chapter 6: Arrays Presentation slides for Java Software Solutions for AP* Computer Science by John Lewis, William Loftus, and Cara Cocking Java Software.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 6: Arrays Presentation slides for Java Software Solutions for AP* Computer Science 3rd Edition.
8-1 Chapter 8: Arrays Arrays are objects that help us organize large amounts of information Today we will focuses on: –array declaration and use –bounds.
Chapter 7 Arrays: Part 2. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Outline Declaring and Using Arrays Arrays of Objects Variable Length Parameter.
CSE 501N Fall ‘09 08: Arrays 22 September 2009 Nicholas Leidenfrost.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 7 Arrays 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
Programming in Java (COP 2250) Lecture Chengyong Yang Fall, 2005.
1 Arrays An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Chapter 7: Arrays.
Chapter 7 Arrays: Part 1 of 2. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of.
Dr. Sahar Shabanah Lecture 3: Arrays. Data Structures Data structures are organized collections of information and a set of operations used to manage.
1 Lecture 6 Objects for Organizing Data Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung Institute of Technology.
1 Sorting b Sorting is the process of arranging a list of items into a particular order b There must be some value on which the order is based b There.
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 7 Arrays 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
1 Objects for Organizing Data -- Introduction zAs our programs get more sophisticated, we need assistance organizing large amounts of data zChapter 6 focuses.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
COS 312 DAY 12 Tony Gauvin. Ch 1 -2 Agenda Questions? First Progress report due Assignment corrected 1 MIA – 2 A’s, 2 B’s, 1 D, 1 F and 1 MIA – Code\pig.
1 Arrays Chapter 8. Objectives You will be able to Use arrays in your Java programs to hold a large number of data items of the same type. Initialize.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 The if-else Statement An else clause can be added to an if statement to make an if-else statement.
Chapter 7 Arrays…. 7-2 Arrays An array is an ordered list of values An array of size N is indexed from.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 6: Arrays Presentation slides for Java Software Solutions for AP* Computer Science 3rd Edition.
Lecture 5 array declaration and instantiation array reference
Arrays of Objects October 9, 2006 ComS 207: Programming I (in Java)
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
Chapter VII: Arrays.
Chapter 6: Arrays Java Software Solutions
Lecture 6 Objects for Organizing Data
COS 312 DAY 14 Tony Gauvin.
Chapter 7: Arrays.
Sorts.
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
Arrays of Objects.
Sorting and Searching -- Introduction
Arrays of Objects October 8, 2007 ComS 207: Programming I (in Java)
Arrays.
Presentation transcript:

Chapter 6: Arrays and Vectors

2 Arrays and Vectors  Arrays and vectors are objects that help us organize large amounts of information  Chapter 6 focuses on: array declaration and usearray declaration and use arrays of objectsarrays of objects sorting elements in an arraysorting elements in an array multidimensional arraysmultidimensional arrays the Vector classthe Vector class using arrays to manage graphicsusing arrays to manage graphics

3 Arrays  An array is an ordered list of values An array of size N is indexed from zero to N-1 scores The entire array has a single name Each value has a numeric index This array holds 10 values that are indexed from 0 to 9

4 Arrays  A particular value in an array is referenced using the array name followed by the index in bracketsusing the array name followed by the index in brackets  For example, scores[4] scores[4] refers to the value 67 (the 5th value in the array)  That expression represents a place to store a single integer, it can be used wherever an integer variable canit can be used wherever an integer variable can it can be assigned a value, printed, used in a calculationit can be assigned a value, printed, used in a calculation

5 Arrays  An array stores multiple values of the same type That type can be primitive types or objectsThat type can be primitive types or objects  Therefore, we can create an array of integers, or an array of characters, or an array of String objects, etc.  In Java, the array itself is an object Therefore the name of the array is a object reference variable, and the array itself is instantiated separatelyTherefore the name of the array is a object reference variable, and the array itself is instantiated separately

6 Declaring Arrays  The scores array could be declared as follows: int[] scores = new int[10]; int[] scores = new int[10];  Note that the type of the array does not specify its size, but each object of that type has a specific size  The type of the variable scores is int[] (an array of integers)  It is set to a new array object that can hold 10 integers  See BasicArray.java (page 270) BasicArray.java

BasicArray.java public class BasicArray { final static int LIMIT = 15; final static int LIMIT = 15; final static int MULTIPLE = 10; final static int MULTIPLE = 10; public static void main (String[] args){ public static void main (String[] args){ int[] list = new int[LIMIT]; int[] list = new int[LIMIT]; // Initialize the array values // Initialize the array values for (int index = 0; index < LIMIT; index++) for (int index = 0; index < LIMIT; index++) list[index] = index * MULTIPLE; list[index] = index * MULTIPLE; list[5] = 999; // change one array value list[5] = 999; // change one array value for (int index = 0; index < LIMIT; index++) for (int index = 0; index < LIMIT; index++) System.out.print (list[index] + " "); System.out.print (list[index] + " "); System.out.println (); System.out.println (); }}

8 Declaring Arrays  Some examples of array declarations: float[] prices = new float[500]; float[] prices = new float[500]; boolean[] flags; boolean[] flags; flags = new boolean[20]; flags = new boolean[20]; char[] codes = new char[1750]; char[] codes = new char[1750];

9 Bounds Checking  Once an array is created, it has a fixed size  An index used in an array reference must specify a valid element That is, the index value must be in bounds (0 to N-1)That is, the index value must be in bounds (0 to N-1)  The Java interpreter will throw an exception if an array index is out of bounds This is called automatic bounds checkingThis is called automatic bounds checking

Bounds Checking  For example, if the array codes can hold 100 values, it can only be indexed using the numbers 0 to 99  If count has the value 100, then the following reference will cause an ArrayOutOfBoundsException : System.out.println (codes[count]);  It’s common to introduce off-by-one errors when using arrays for (int index=0; index <= 100; index++) codes[index] = index*50 + epsilon; problem

11 Bounds Checking  Each array object has a public constant called length that stores the size of the array  It is referenced using the array name (just like any other object): scores.length scores.length  Note that length holds the number of elements, not the largest index  See ReverseNumbers.java (page 272) ReverseNumbers.java  See LetterCount.java (page 274) LetterCount.java

// Reads a set of integers from the user, storing them in // Reads a set of integers from the user, storing them in // an array, then prints them in the opposite order. // an array, then prints them in the opposite order. Import cs1.Keyboard class Reverse_Numbers { public static void main (String[] args) { public static void main (String[] args) { double[] numbers = new double[10]; double[] numbers = new double[10]; System.out.println ("The size of the array is: " +numbers.length); System.out.println ("The size of the array is: " +numbers.length); for (int index = 0; index < numbers.length; index++) { for (int index = 0; index < numbers.length; index++) { System.out.print ( ” Enter number " + (index +1) + ": "); System.out.print ( ” Enter number " + (index +1) + ": "); numbers[index] = Keyboard.readDouble(); numbers[index] = Keyboard.readDouble(); } System.out.println ("Numbers in reverse:"); for (int index = numbers.length-1; index >= 0; index--) System.out.print (numbers[index] + " "); System.out.print (numbers[index] + " "); System.out.println (); System.out.println (); } // method main } // method main } // class Reverse_Numbers Reverse_Numbers.java

13 Array Declarations Revisited  The brackets of the array type can be associated with the element type or with the name of the array  Therefore the following declarations are equivalent: float[] prices; float[] prices; float prices[]; float prices[];  The first format is generally more readable

14 Initializer Lists  An initializer list can be used to instantiate and initialize an array in one step  The values are delimited by braces and separated by commas  Examples: int[] units = {147, 323, 89, 933, 540, int[] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476}; 269, 97, 114, 298, 476}; char[] letterGrades = {'A', 'B', 'C', 'D', 'F'}; char[] letterGrades = {'A', 'B', 'C', 'D', 'F'};

15 Initializer Lists  Note that when an initializer list is used: the new operator is not usedthe new operator is not used no size value is specifiedno size value is specified  The size of the array is determined by the number of items in the initializer list  An initializer list can only be used in the declaration of an array  See Primes.java (page 278) Primes.java

16 Arrays as Parameters  An entire array can be passed to a method as a parameter  Like any other object, the reference to the array is passed, making the formal and actual parameters aliases of each other  Changing an array element in the method changes the original  An array element can be passed to a method as well, and will follow the parameter passing rules of that element's type

17 Arrays of Objects  The elements of an array can be object references  The following declaration reserves space to store 25 references to String objects String[] words = new String[25]; String[] words = new String[25];  It does NOT create the String objects themselves  Each object stored in an array must be instantiated separately  See GradeRange.java (page 280) GradeRange.java

Array of Objects Words[0] = new String(“1st string”); words 1st string

GradeRange.java public class GradeRange { // Stores the possible grades and their numeric lowest value, // Stores the possible grades and their numeric lowest value, // then prints them out. // then prints them out. public static void main (String[] args) public static void main (String[] args) { String[] grades = {"A", "A-", "B+", "B", "B-", "C+", "C", "C-", String[] grades = {"A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D+", "D", "D-", "F"}; "D+", "D", "D-", "F"}; int[] cutoff = {95, 90, 87, 83, 80, 77, 73, 70, 67, 63, 60, 0}; int[] cutoff = {95, 90, 87, 83, 80, 77, 73, 70, 67, 63, 60, 0}; for (int level = 0; level < cutoff.length; level++) for (int level = 0; level < cutoff.length; level++) System.out.println (grades[level] + "\t" + cutoff[level]); System.out.println (grades[level] + "\t" + cutoff[level]); }}

Command-Line Arguments  The signature of the main method indicates that it takes an array of String objects as a parameter These values come from command-line arguments that are provided when the interpreter is invokedThese values come from command-line arguments that are provided when the interpreter is invoked  For example, > java DoIt pennsylvania texas california These strings are stored at indexes 0-2 of the parameterThese strings are stored at indexes 0-2 of the parameter  See NameTag.java (page 281) NameTag.java

NameTag.java public class NameTag { // Prints a simple name tag using a greeting and a name // Prints a simple name tag using a greeting and a name // that is specified by the user. // that is specified by the user. public static void main (String[] args) { public static void main (String[] args) { System.out.println (); System.out.println (); System.out.println (" " + args[0]); System.out.println (" " + args[0]); System.out.println ("My name is " + args[1]); System.out.println ("My name is " + args[1]); System.out.println (); System.out.println (); }}

22 Arrays of Objects  Objects can have arrays as instance variables  Therefore, fairly complex structures can be created simply with arrays and objects  The software designer must carefully determine an organization of data and objects that makes sense for the situation  See Tunes.java (page 282) Tunes.java  See CDCollection.java (page 284) CDCollection.java  See CD.java (page 286) CD.java

Tunes.java import CDCollection; public class Tunes { // Creates a CDCollection object and adds some CDs to it. // Creates a CDCollection object and adds some CDs to it. // Prints reports on the status of the collection. // Prints reports on the status of the collection. public static void main (String[] args) { public static void main (String[] args) { CDCollection music = new CDCollection (); CDCollection music = new CDCollection (); music.addCD ("Storm Front", "Billy Joel", 14.95, 10); music.addCD ("Storm Front", "Billy Joel", 14.95, 10); music.addCD ("Come On Over", "Shania Twain", 14.95, 16); music.addCD ("Come On Over", "Shania Twain", 14.95, 16); music.addCD ("Soundtrack", "Les Miserables", 17.95, 33); music.addCD ("Soundtrack", "Les Miserables", 17.95, 33); music.addCD ("Graceland", "Paul Simon", 13.90, 11); music.addCD ("Graceland", "Paul Simon", 13.90, 11); System.out.println (music); System.out.println (music); music.addCD ("Double Live", "Garth Brooks", 19.99, 26); music.addCD ("Double Live", "Garth Brooks", 19.99, 26); music.addCD ("Greatest Hits", "Jimmy Buffet", 15.95, 13); music.addCD ("Greatest Hits", "Jimmy Buffet", 15.95, 13); System.out.println (music); System.out.println (music); }}

CDCollection.java import CD; import java.text.NumberFormat; public class CDCollection { private CD[] collection; private CD[] collection; private int count; private int count; private double totalValue; private double totalValue; private int currentSize; private int currentSize; // Creates an initially empty collection. // Creates an initially empty collection. public CDCollection ( ) { public CDCollection ( ) { currentSize = 100; currentSize = 100; collection = new CD[currentSize]; collection = new CD[currentSize]; count = 0; count = 0; totalValue = 0.0; totalValue = 0.0; } // //

CDCollection.java // Adds a CD to the collection, increasing the size of the // Adds a CD to the collection, increasing the size of the // collection if necessary. // collection if necessary. public void addCD (String title, String artist, double value, public void addCD (String title, String artist, double value, int tracks) int tracks) { if (count == currentSize) if (count == currentSize) increaseSize(); increaseSize(); collection[count] = new CD (title, artist, value, tracks); collection[count] = new CD (title, artist, value, tracks); totalValue += value; totalValue += value; count++; count++; }

CDCollection.java // Returns a report describing the CD collection. // Returns a report describing the CD collection. public String toString( ) { public String toString( ) { NumberFormat fmt = NumberFormat.getCurrencyInstance(); NumberFormat fmt = NumberFormat.getCurrencyInstance(); String report = "&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n"; String report = "&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n"; report += "My CD Collection\n\n"; report += "My CD Collection\n\n"; report += "Number of CDs: " + count + "\n"; report += "Number of CDs: " + count + "\n"; report += "Total value: " + fmt.format(totalValue) + "\n"; report += "Total value: " + fmt.format(totalValue) + "\n"; report += "Average cost: " + fmt.format(totalValue/count); report += "Average cost: " + fmt.format(totalValue/count); report += "\n\nCD List:\n\n"; report += "\n\nCD List:\n\n"; for (int cd = 0; cd < count; cd++) for (int cd = 0; cd < count; cd++) report += collection[cd].toString() + "\n"; report += collection[cd].toString() + "\n"; return report; return report; }

CDCollection.java // Doubles the size of the collection by creating a larger array // Doubles the size of the collection by creating a larger array // and copying into it the existing collection. // and copying into it the existing collection. private void increaseSize () { private void increaseSize () { currentSize *= 2; currentSize *= 2; CD[] temp = new CD[currentSize]; CD[] temp = new CD[currentSize]; for (int cd = 0; cd < collection.length; cd++) for (int cd = 0; cd < collection.length; cd++) temp[cd] = collection[cd]; temp[cd] = collection[cd]; collection = temp; collection = temp; }}

CD.java import java.text.NumberFormat; public class CD { private String title, artist; private String title, artist; private double value; private double value; private int tracks; private int tracks; // Creates a new CD with the specified information. // Creates a new CD with the specified information. public CD (String theTitle, String theArtist, double theValue, public CD (String theTitle, String theArtist, double theValue, int theTracks) { int theTracks) { title = theTitle; title = theTitle; artist = theArtist; artist = theArtist; value = theValue; value = theValue; tracks = theTracks; tracks = theTracks; }

CD.java // Returns a description of this CD. // Returns a description of this CD. public String toString( ){ public String toString( ){ NumberFormat fmt = NumberFormat.getCurrencyInstance(); NumberFormat fmt = NumberFormat.getCurrencyInstance(); String description; String description; description = fmt.format(value) + "\t" + tracks + "\t"; description = fmt.format(value) + "\t" + tracks + "\t"; description += title + "\t" + artist; description += title + "\t" + artist; return description; return description; }}

30 Sorting  Sorting is the process of arranging a list of items into a particular order  There must be some value on which the order is based  There are many algorithms for sorting a list of items  These algorithms vary in efficiency  We will examine two specific algorithms: Selection SortSelection Sort Insertion SortInsertion Sort

31 Selection Sort  The approach of Selection Sort: select one value and put it in its final place in the sort listselect one value and put it in its final place in the sort list repeat for all other valuesrepeat for all other values  In more detail: find the smallest value in the listfind the smallest value in the list switch it with the value in the first positionswitch it with the value in the first position find the next smallest value in the listfind the next smallest value in the list switch it with the value in the second positionswitch it with the value in the second position repeat until all values are placedrepeat until all values are placed

32 Selection Sort  An example: original: original: smallest is 1: smallest is 1: smallest is 2: smallest is 2: smallest is 3: smallest is 3: smallest is 6: smallest is 6:  See SortGrades.java (page 289) SortGrades.java  See Sorts.java (page 290) -- the selectionSort method Sorts.java Sorts.java

33 Insertion Sort  The approach of Insertion Sort: Pick any item and insert it into its proper place in a sorted sublistPick any item and insert it into its proper place in a sorted sublist repeat until all items have been insertedrepeat until all items have been inserted  In more detail: consider the first item to be a sorted sublist (of one item)consider the first item to be a sorted sublist (of one item) insert the second item into the sorted sublist, shifting items as necessary to make room to insert the new additioninsert the second item into the sorted sublist, shifting items as necessary to make room to insert the new addition insert the third item into the sorted sublist (of two items), shifting as necessaryinsert the third item into the sorted sublist (of two items), shifting as necessary repeat until all values are inserted into their proper positionrepeat until all values are inserted into their proper position

34 Insertion Sort  An example: original: original: insert 9: insert 9: insert 6: insert 6: insert 1: insert 1: insert 2: insert 2:  See Sorts.java (page 290) -- the insertionSort method Sorts.java

35 Sorting Objects  Integers have an inherent order, but the order of a set of objects must be defined by the person defining the class  Recall that a Java interface can be used as a type name and guarantees that a particular class has implemented particular methods  We can use the Comparable interface to develop a generic sort for a set of objects  See SortPhoneList.java (page 294) SortPhoneList.java  See Contact.java (page 295) Contact.java  See Sorts.java (page 290) Sorts.java

36 Comparing Sorts  Both Selection and Insertion sorts are similar in efficiency  The both have outer loops that scan all elements, and inner loops that compare the value of the outer loop with almost all values in the list  Therefore approximately n 2 number of comparisons are made to sort a list of size n  We therefore say that these sorts are of order n 2  Other sorts are more efficient: order n log 2 n

37 Two-Dimensional Arrays  A one-dimensional array stores a simple list of values  A two-dimensional array can be thought of as a table of values, with rows and columns  A two-dimensional array element is referenced using two index values  To be precise, a two-dimensional array in Java is an array of arrays  See TwoDArray.java (page 299) TwoDArray.java

TwoDArray.java public class TwoDArray { // Creates a 2D array of integers, fills it with increasing // Creates a 2D array of integers, fills it with increasing // integer values, then prints them out. // integer values, then prints them out. public static void main (String[] args) { public static void main (String[] args) { int[][] table = new int[5][10]; int[][] table = new int[5][10]; // Load the table with values // Load the table with values for (int row=0; row < table.length; row++) for (int row=0; row < table.length; row++) for (int col=0; col < table[row].length; col++) for (int col=0; col < table[row].length; col++) table[row][col] = row * 10 + col; table[row][col] = row * 10 + col; // Print the table // Print the table for (int row=0; row < table.length; row++) { for (int row=0; row < table.length; row++) { for (int col=0; col < table[row].length; col++) for (int col=0; col < table[row].length; col++) System.out.print (table[row][col] + "\t"); System.out.print (table[row][col] + "\t"); System.out.println(); System.out.println(); } }}

39 Multidimensional Arrays  An array can have as many dimensions as needed, creating a multidimensional array  Each dimension subdivides the previous one into the specified number of elements  Each array dimension has its own length constant  Because each dimension is an array of array references, the arrays within one dimension could be of different lengths

40 The Vector Class  An object of class Vector is similar to an array in that it stores multiple values  However, a vector only stores objectsonly stores objects does not have the indexing syntax that arrays havedoes not have the indexing syntax that arrays have  The methods of the Vector class are used to interact with the elements of a vector  The Vector class is part of the java.util package  See Beatles.java (page 304) Beatles.java Beatles.java

Beatles.java import java.util.Vector; public class Beatles { // Stores and modifies band members. public static void main (String[] args) { public static void main (String[] args) { Vector band = new Vector(); Vector band = new Vector(); band.addElement ("Paul"); band.addElement ("Paul"); band.addElement ("Pete"); band.addElement ("Pete"); band.addElement ("John"); band.addElement ("John"); band.addElement ("George"); band.addElement ("George"); System.out.println (band); System.out.println (band); band.removeElement ("Pete"); band.removeElement ("Pete"); System.out.println (band); System.out.println (band); System.out.println ("At index 1: " + band.elementAt(1)); System.out.println ("At index 1: " + band.elementAt(1)); band.insertElementAt ("Ringo", 2); band.insertElementAt ("Ringo", 2); System.out.println (band); System.out.println (band); System.out.println ("Size of the band: " + band.size()); System.out.println ("Size of the band: " + band.size()); }}

42 The Vector Class  An important difference between an array and a vector is that a vector can be thought of as a dynamic, able to change its size as needed  Each vector initially has a certain amount of memory space reserved for storing elements  If an element is added that doesn't fit in the existing space, more room is automatically acquired

43 The Vector Class  The Vector class is implemented using an array  Whenever new space is required, a new, larger array is created, and the values are copied from the original to the new array  To insert an element, existing elements are first copied, one by one, to another position in the array  Therefore, the implementation of Vector in the API is not very efficient for inserting elements

Polygons and Polylines  Arrays are often helpful in graphics processing  Polygons and polylines are shapes that are defined by values stored in arrays  A polyline is similar to a polygon except that its endpoints do not meet, and it cannot be filled  See Rocket.java (page 307) Rocket.java  There is also a separate Polygon class that can be used to define and draw a polygon

Rocket.java import java.applet.Applet; import java.awt.*; public class Rocket extends Applet { private final int APPLET_WIDTH = 200; private final int APPLET_WIDTH = 200; private final int APPLET_HEIGHT = 200; private final int APPLET_HEIGHT = 200; private int[] xRocket = {100, 120, 120, 130, 130, 70, 70, 80, 80}; private int[] xRocket = {100, 120, 120, 130, 130, 70, 70, 80, 80}; private int[] yRocket = {15, 40, 115, 125, 150, 150, 125, 115, 40}; private int[] yRocket = {15, 40, 115, 125, 150, 150, 125, 115, 40}; private int[] xWindow = {95, 105, 110, 90}; private int[] xWindow = {95, 105, 110, 90}; private int[] yWindow = {45, 45, 70, 70}; private int[] yWindow = {45, 45, 70, 70}; private int[] xFlame = {70, 70, 75, 80, 90, 100, 110, 115, 120, private int[] xFlame = {70, 70, 75, 80, 90, 100, 110, 115, 120, 130, 130}; 130, 130}; private int[] yFlame = {155, 170, 165, 190, 170, 175, 160, 185, private int[] yFlame = {155, 170, 165, 190, 170, 175, 160, 185, 160, 175, 155}; 160, 175, 155};

Rocket.java // Sets up the basic applet environment. // Sets up the basic applet environment. public void init() { public void init() { setBackground (Color.black); setBackground (Color.black); setSize (APPLET_WIDTH, APPLET_HEIGHT); setSize (APPLET_WIDTH, APPLET_HEIGHT); } // Draws a rocket using polygons. // Draws a rocket using polygons. public void paint (Graphics page) { public void paint (Graphics page) { page.setColor (Color.cyan); page.setColor (Color.cyan); page.fillPolygon (xRocket, yRocket, xRocket.length); page.fillPolygon (xRocket, yRocket, xRocket.length); page.setColor (Color.gray); page.setColor (Color.gray); page.fillPolygon (xWindow, yWindow, xWindow.length); page.fillPolygon (xWindow, yWindow, xWindow.length); page.setColor (Color.red); page.setColor (Color.red); page.drawPolyline (xFlame, yFlame, xFlame.length); page.drawPolyline (xFlame, yFlame, xFlame.length); }}

Saving Drawing State  Each time the repaint method is called on an applet, the window is cleared prior to calling paint  An array or vector can be used to store the objects drawn, and redraw them as necessary  See Dots2.java (page 310) Dots2.java Dots2.java

Dots2.java import java.applet.Applet; import java.awt.*; import java.awt.event.*;import java.util.* public class Dots2 extends Applet implements MouseListener { private final int APPLET_WIDTH = 200; private final int APPLET_WIDTH = 200; private final int APPLET_HEIGHT = 100; private final int APPLET_HEIGHT = 100; private final int RADIUS = 6; private final int RADIUS = 6; private Point clickPoint = null; private Point clickPoint = null; private Vector pointList; private Vector pointList; private int count; private int count; // Creates a Vector object to store the points. // Creates a Vector object to store the points. public void init() { public void init() { pointList = new Vector(); pointList = new Vector(); count = 0; count = 0; addMouseListener(this); addMouseListener(this); setBackground (Color.black); setBackground (Color.black); setSize (APPLET_WIDTH, APPLET_HEIGHT); setSize (APPLET_WIDTH, APPLET_HEIGHT); } // //

Dots2.java // Draws all of the dots stored in the Vector. // Draws all of the dots stored in the Vector. public void paint (Graphics page) { public void paint (Graphics page) { page.setColor (Color.green); page.setColor (Color.green); // Retrieve an iterator for the vector of points // Retrieve an iterator for the vector of points Iterator pointIterator = pointList.iterator(); Iterator pointIterator = pointList.iterator(); while (pointIterator.hasNext()) while (pointIterator.hasNext()) { Point drawPoint = (Point) pointIterator.next(); Point drawPoint = (Point) pointIterator.next(); page.fillOval (drawPoint.x - RADIUS, drawPoint.y - RADIUS, page.fillOval (drawPoint.x - RADIUS, drawPoint.y - RADIUS, RADIUS * 2, RADIUS * 2); RADIUS * 2, RADIUS * 2); } page.drawString ("Count: " + count, 5, 15); page.drawString ("Count: " + count, 5, 15); }

Dots2.java // Adds the current point to the list of points and redraws the // Adds the current point to the list of points and redraws the // applet whenever the mouse is pressed. // applet whenever the mouse is pressed. public void mousePressed (MouseEvent event) { public void mousePressed (MouseEvent event) { pointList.addElement (event.getPoint()); pointList.addElement (event.getPoint()); count++; count++; repaint(); repaint(); } // Provide empty definitions for unused event methods. // Provide empty definitions for unused event methods. public void mouseClicked (MouseEvent event) {} public void mouseClicked (MouseEvent event) {} public void mouseReleased (MouseEvent event) {} public void mouseReleased (MouseEvent event) {} public void mouseEntered (MouseEvent event) {} public void mouseEntered (MouseEvent event) {} public void mouseExited (MouseEvent event) {} public void mouseExited (MouseEvent event) {}}