Download

# ARRAYS

Download Presentation

## ARRAYS

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
##### Presentation Transcript

1. [0] [1] [2] [3] [4] [5] [6] [7] C S C I 0 1 5 0 ARRAYS • Why Use Arrays • Syntax • Multi-Dimensional Arrays • Array Lists • Generics

2. Why Use Arrays? • Until now, we have used variables that hold references only to single objects • But what if want to hold lots of data? Many programs need to keep track of hundreds (or hundreds of thousands) of data pieces • Want to hold arbitrary number of objects with single reference • represents collection of elements • can send messages to multiple elements much more easily • Arrays are oldest form of composite data structure, first found in FORTRAN (FORmulaTRANslator, 1955), first high-level programming language, designed by John Backus et al at IBM for number-crunching and still in use today: “FORTRAN is a hardy weed…” • Arrays are the simplest collection – we’ll study stacks, queues, linked lists and trees

3. Fibonacci Sequence • Suppose we want to keep track of first 20 numbers in Fibonacci sequence • sequence begins with zero and one • successive numbers are determined by adding previous two numbers • third number: add first and second numbers (0+1=1) • fourth number: add second and third numbers (1+1=2); • and so on... • Beginning of sequence looks like this: 0 1 1 2 3 5 8 13 21 34 55 89 • We could do it with instance variables... public class FibSequence { private int _firstNum, _secondNum, _thirdNum, ... _twentiethNum; } • This gets tiresome and is not very flexible • try making a sequence with forty numbers • now try it with a thousand!

4. Arrays • Arrays store a specified, constant number of homogeneous (same type) data elements • simplest homogeneous collection • each element must be same type or subclass of same type • Arrays are special in Java • provide special syntax to access array elements: _studentArray[index] • neither base type nor class, but Java construct • cannot subclass • only methods are those defined by Object class • and we won’t use those… • new to initialize an array (even though it’s not a class!) • Arrays hold only elements of specified type • when declaring array, state type of object that array stores (base type, class, or for max polymorphic flexibility, interface) • if storing class, can put references to instances of only that class (or subclasses) into array • Note: you could declare array to be of java.lang.Object type to store any instance, but not useful: wouldn’t take advantage of compiler’s type-checking…

5. Arrays (cont.) • Every array element is an object reference or base type. What real-world objects could we organize with arrays? • floors of building • streets in Manhattan • strings representing names of people in a course • Elements are ordered sequentially by numerical index • in mathematics, we refer to related variables by using subscript notation, i.e., A1, A2, A3, ... An • with Java, represent index inside brackets, i.e., array[0], array[1], ... array[n-1] • Arrays store objects in numbered slots • for array of size n, first index is always 0, last index is always n-1 • Common graphical representations of arrays: [0] [1] [2] [3] [18] [19] [0] [1] [2] [3] [4] [5] [17] [18] [19]

6. [0] [1] [2] [3] [4] [5] [6] [7] Array Examples • The SunlabComputers • Array size: • Array index: • Element type: 72 node number computer Note: This could also be modeled as a 2D array (see slide 17) • Houses on a Neighborhood Street • Array size:Element type: • Array index: 8 house house number Note: arrays don’t need to be full (e.g., no house 0 or 7)

7. Java’s Syntax for Arrays • Declaration: <type>[] <array-name>; • <type> denotes data type that the array is to hold in each slot: can be class, base type, interface, or even another array (for nested arrays) • Colorable[] myColorables; declares a one-dimensional array that holds references to instances of classes that implement Colorable interface • Note: unlike some other programming languages, size of array not specified in declaration, but in initialization; • also no reserved word “array” – brackets suffice • Initialization <array-name> = new <type>[<size>]; • <size> must be an integer value greater than 0; indices will range from 0 to <size> - 1 // here we initialize array after declaring it Colorable[] myColorables; myColorables = new Colorable[10]; • note only array is initialized, not elements of array; all references are set to null, 0 for ints, false for booleans, etc. // alternatively we can declare and initialize // in one statement, just like we can with // objects and base types Colorable[] otherColorables = new Colorable[5];

8. Java’s Syntax for Arrays (cont.) • Accessing individual elements: <array-name>[<index>] • index must be an integer between 0 and (array_size - 1) • result is the variable stored at that index • if index is greater than or equal to size, or less than 0, an ArrayIndexOutOfBoundsException is thrown • Anywhere that you can use a variable or a constant, you can also use an array element. For example, in your DrawingPanel: // initialize first element of an array of // Colorables to be an Ellipse myColorables[0] = new gfx.Ellipse(this); // send a message to 3rd element of the array // assume myColorables[2] is not null myColorables[2].setColor(java.awt.Color.RED); // assign fourth element of array to // a local variable ColorablemyColorableVar = myColorables[3]; // pass 5th element of the array as parameter _myPaintShop.paintRandomColor(myColorables[4]); • Note: in some other languages, index can run between any two integers (m,n), where m<n

9. Arrays as Parameters • Can pass in an entire array as parameter by adding array brackets to type of formal parameter public int sum(int[] numbers) { // code to compute sum of elements in the // numbers array } • But how do we determine size of array? • could pass a second parameter, specifying size • arrays have their length as a public property • use special “dot” syntax to find out length; here we inquire it and then store it for future use intarrayLength = <array-name>.length; How might you use this in an actual piece of code? public int sum(int[] numbers) { int total = 0; for (inti = 0; i < numbers.length; i++) { total += numbers[i]; } return total; } • What if the code read i <= numbers.length? • “off-by-one” error – go thru loop once too often

10. Example: Making Cookies • Here is the specification: Design and implement a Java program with ten factories, each specializing in its particular kind of cookie, which generate their cookies in a row at the top of the frame. When “Create Cookies” button is pressed, all factories should make a cookie just below the factory’s position and drop it so it falls down and then out of the frame.

11. Quick Look at Design • Finding the important nouns Design and implement a Java program with ten factories, each specializing in its particular kind of cookie, whichgenerate their cookiesin a rowat the top of the panel. When “Create Cookies” buttonis pressed, all factoriesshould make a cookiejust below the factory’s position and drop it so it falls down and then out of the panel. • Some things we’ve seen before: • Factory– constructs other classes without knowing actual type of object to be constructed • Java program– uses a javax.swing.JFrame • panel– JPanel,cookiesare images graphically contained in a panel • cookie– java.awt.Image that has behavior to move down panel • row–javax.swing.JPanel to layout cookiefactories • position: set using methods of our specialized java.awt.Image class • Things that aren’t as apparent: • how do we make buttondo something for all factories in sequence? • how do we deal with ten cookie factoriesusefully?

12. ‘Create DropButton’ Button • DropButtonextends javax.swing.JButton and adds a java.awt.event.ActionListener that does something useful package Demos.CookieArray; public class DropButton extends javax.swing.JButton { // CookieFactory is defined elsewhere // (actual definition is not important here) private CookieFactory[] _cookieFactoryArray; public DropButton(CookieFactory[] cfArray) { super("Create Cookies”); _cookieFactoryArray = cfArray; this.addActionListener(new DropListener()); } private class DropListener implements java.awt.event.ActionListener { public void actionPerformed (java.awt.event.ActionEvent e){ // when button is pressed, use loop to tell // every Factory in array to makeCookie for(inti = 0; i < _cookieFactoryArray.length; i++) { _cookieFactoryArray[i].makeCookie(); } } } // end of inner class DropListener } // end of class DropButton

13. Out-of-Bounds Problems • Be careful about bounds of loops that access arrays: • Java will throw ArrayIndexOutOfBoundsException if index is negative since sequence starts at 0 • Java will throw ArrayIndexOutOfBoundsException if index is greater than or equal to array size; remember that the array goes from 0 to n-1 • exceptions can lead to crashes so be careful • Java has a catch keyword which can be used to “catch” and handle exceptions … used in CS16 • Prevent out-of-bounds problems by explicitly checking with conditionals before accessing public booleanisIndexInBounds(int index) { return ((index >= 0) && (index < _factoryArray.length)); } • don’t need to do this in for loop, but could be useful in indefinite loop • Remember the power of hand simulation! • In general, important to check for legal values of parameters yourself to prevent problems (don’t always have to make a different method to do this check, though)

14. Multi-Dimensional Arrays • Say we wanted to model a chess board • not a linear group of squares • more like a grid of squares • Can declare an array to be 2 (or more) dimensions, by adding more brackets • one pair per dimension • 2D: int[][] grid = new int[a][b]; • 3D: int[][][] cube = new int[x][y][z]; // Values of a, b, x, y, z set elsewhere • Multi-dimensional array is an array of arrays of… • The syntax above is for rectangular, cuboid, etc. multi-dimensional arrays • since multi-dimensional arrays are just arrays of arrays, possible (using different syntax) to have jagged arrays, where each sub-array is of a different length • thus can have a “triangle” shaped array • don’t use this in CS15; even beyond CS15, it is unlikely you will use this

15. Representing Multi-Dimensional arrays • Let’s say we want to represent this grid of numbers: • How do we want to represent this grid? There are two equally valid options: 1 2 3 4 5 6 rows 7 8 9 columns 1 2 3 1 2 3 4 5 6 4 5 6 7 8 9 7 8 9 Array of columns Array of rows

16. Ways to Think About Array Storage • Multi-dimensional arrays in Java do not make a distinction between rows or columns – think about a one-dimensional array - doesn’t really matter if we call it a “row” or “column” (unlike in many other languages!) • So the following two visualizations of a two-dimensional array (called array ) are equally valid: • Visualization is less important than indexing – make sure you are consistent in the way you index into your 2D array throughout your program! row-major order, i.e., first index is row index (purple ball is still at array[0][2] – but now, 0th row, 2nd column) column-major order, i.e., first index is column index (e.g., purple ball is at array[0][2] – 0th column, 2nd row)

17. Two-Dimensional Array Examples • Pixel Array • 2D Array size: • Array indices: • Element type: pxlwidth by pxlheight x, y RGB color • Connect Four • 2D array size: • Array indices: • Element type: 6 by 7 row, column checker • The Sunlab as a 2D array! • Array size: • Array indices: • Element type: 10 by 8 (est) row, column computer

18. F T F F F F F F F F F F F T F x 0 1 2 3 4 0 1 2 (1, 0) y (3, 2) Thinking About Arrays for Graphics • Consider a 2D array of booleans where you want to turn on a pixel for each true value at the corresponding (row, column) position • instead of Boolean, could store pixel’s color value • In computer graphics, think column-major order, i.e., 1st index as x coordinate and 2nd as y coordinate • each x-coordinate holds an array of y-coordinates x-coordinates y-coordinates grid[3][2]

19. Example: Size of 2D Arrays public class ArraySize { //using rows and columns as indices is arbitrary private static final int NUM_ROWS = 10; private static final int NUM_COLS = 5; public ArraySize() { // String is just an arbitrary choice! String[][] myArray = new String[NUM_ROWS][NUM_COLS]; System.out.println( “Number of rows = ” + NUM_ROWS); System.out.println( “Number of columns = ” + NUM_COLS); System.out.println( “Size of array = ” + this.find2DArraySize(myArray)); } public int find2DArraySize(String[][] array){ intnumRows = array.length; intnumCols = array[0].length; // element 0 is return (numRows * numCols); // an array } } array.lengthgives the size of the first dimension (you decide whether that is the row or column) array[0].length gives the size of the second dimension

20. Common Array Errors – Watch Out! • Assigning a scalar to an array int[] myArray = 5; • 5 is not an array, it is an element • to initialize array elements you must loop over the array and assign values at each index int[] myArray = new int[20]; for (inti=0; i < myArray.length; i++) { myArray[i] = 5; } • Assigning an array to a scalar int[] myArray = new int[1000]; intmyInt = myArray; • Assigning arrays of different dimension to each other int[] myIntArray = new int[23]; int[][] my2DIntArray = new int[2][34]; myIntArray = my2DIntArray; • Never assign arrays of different dimensions or you will become familiar with the error: “Incompatible type for =. Can’t convert int[] to int[][]” similar message for assigning arrays of the wrong type

21. Let’s Make a Board ... What Kind? • Warm-up for Tetris… • Let’s start with a specification: Write a Java program that draws sixty-four squares in a grid-like pattern of alternating colors, much like a checker board. The checker board should be eight squares long and eight squares wide. Additionally, the user should be able to click on buttons and change the colors in an individual row or column of the board from the traditional red and black to the new & bold colors white and blue. There should be sliders that allow the user to select which row or column should switch its colors when a button is pressed.

22. Quick Look at Design • Finding the important nouns Write a Java program that draws sixty-four squares in a grid-like pattern of alternating colors, much like a checkerboard. The checker boardshould be eight squareslong and eight squareswide. Additionally, the usershould be able to click on buttonsand change the colorsin an individual row or columnof the boardfrom the traditional redand blackto the new, bold colorswhiteand blue. There should be slidersthat allow the userto select which row or columnshould switch its colorswhen a buttonis pressed. • Some things we’ve seen before: • java program – uses a javax.swing.JFrame • buttons – uses javax.swing.JButtons • slider– (JSlider) component for choosing one of many numeric values • red, black, white, blue–java.awt.Colors • Things that aren’t as apparent • sixty-four squares – we know about one square, ColorShape.Rectangle, but 64? • checker board– let’s make a 2D 8x8 array of squares • row, column– indices into array • This sample program has crucial design hints for Tetris. Pay close attention!

23. Building Square that Changes Colors • Stores 2 colors and toggles between them package Demos.CheckerArray; import static Demos.CheckerArray.CheckerBoardConstants.*; public class ColorChangingRect extends gfx.Rectangle { private java.awt.Color _currentColor, _otherColor; public ColorChangingRect( DrawingPaneldp, java.awt.ColortradColor, java.awt.ColorboldColor) { super(dp); // SQR_SIZE defined in CheckerBoardConstants this.setSize(SQR_SIZE, SQR_SIZE); // store the two colorparms to toggle between _currentColor = tradColor; _otherColor = boldColor; this.setColor(_currentColor); } public void toggleColor() { // standard pattern for swapping two colors: // must use temporary variable to store // color that is replaced in first step java.awt.Color temp = _currentColor; _currentColor = _otherColor; _otherColor = temp; this.setColor(_currentColor); } } // end of class ColorChangingRect

24. Building Checkerboard • Let’s start with standard stuff • contains array of ColorChangingRects • extends JPanel • We will think of the locations of the ColorChangingRects in terms of columns (x coordinates) and rows (y coordinates), so the first index will be column, the second row package Demos.CheckerArray; import static Demos.CheckerArray.CheckerBoardConstants.*; /** * Class that represents checkerboard. It * contains a 2D array of ColorChangingRects * to manage squares so they can be accessed * and changed later. **/ public class CheckerBoard extends JPanel { private ColorChangingRect[][] _rects; // call to super() elided public CheckerBoard() { Dimension size = new Dimension (NUM_SQRS*SQR_SIZE, NUM_SQRS*SQR_SIZE)); // NUM_SQRS defined in CheckerBoardConstants this.setSize(size); this.setPreferredSize(size) _rects = new ColorChangingRect[NUM_SQRS][NUM_SQRS]; // continued . . .

25. Initializing Array with Colored Squares • Initialize a ColorChangingRect to right color for its position in array, then set its location on board, then add it to array • first index (x) is column, second (y) is row // first for loop loops through columns for (intcol = 0; col < NUM_SQRS; col++) { // nested for loop loops through rows for (int row = 0; row < NUM_SQRS; row++) { ColorChangingRectrect; // every second square should be red if (((row + col) % 2) == 0) { rect = new ColorChangingRect(this, java.awt.Color.RED, java.awt.Color.WHITE); } else { rect = new ColorChangingRect(this, java.awt.Color.BLACK, java.awt.Color.BLUE); } // rect's location on board determined by // its index in array and its size rect.setLocation(col * SQR_SIZE, row * SQR_SIZE )); _rects[col][row] = rect; } // end of nested for loop } // end of first for loop } // end of constructor // other methods here } // end of class CheckerBoard

26. Linking Buttons To Slider • We want one object’s property to depend on another object’s property • e.g., the current row number changes depending on current value of slider • ChangeColorButton • superclass that will have two subclasses, one for changing color of a row of squares and another for changing color of a column of squares. Subclasses (next slide) will specify ActionListener • actionPerformed() will get the row or column value from _slider and call changeRowColor() (or column color) package Demos.CheckerArray; public class ChangeColorButton extends javax.swing.JButton { //note the use of protected instance variables protected CheckerBoard _board; //need reference to slider to get its value protected javax.swing.JSlider _slider; public ChangeColorButton(CheckerBoard board, javax.swing.JSlider slider){ super(“Change Color”); _board = board; _slider = slider; } }// end of class ChangeColorButton

27. Updating Squares (cont.) • Button subclasses send message to CheckerBoardto change color of squares in specified column or row package Demos.CheckerArray; public class ChangeRowColorButton extends ChangeColorButton { public ChangeRowColorButton(CheckerBoard board, JSlider slider) { super(board, slider); this.addActionListener(new ClickListener()); } private class ClickListener implements ActionListener { public void actionPerformed(ActionEvent e) { _board.changeRowColor(_slider.getValue()); } // _slider a protected instance variable } } // in CheckerBoard class... public void changeRowColor(int row) { for (intcol = 0; col < NUM_SQRS; col++) { // local variable points to selected rect ColorChangingRectrect = _rects[col][row]; // make sure value of array element isn’t null // (i.e., array initialized correctly) if (rect != null) rect.toggleColor(); } } • ChangeColumnColorButton and changeColumnColor method are similar to these

28. java.util.ArrayList • java.util.ArrayLists, like arrays, hold references to many objects of same data type • Another kind of collection, also using an index, but much easier management of update dynamics • Differences: • don’t need to be initialized with size – can hold an arbitrary number of references • are Java classes, so have methods • Why use them instead of arrays? • when number of elements to be held is unknown • making array too small leads to bugs or crashes • making array too large is inefficient, takes up more memory than necessary • handles update dynamics (shifting elements in memory) for you • Why use arrays instead of array lists? • want something simple • want to use less memory (when expect both array and array list to hold same number of elements) • want faster operations

29. Adding and Deleting in Arrays When adding at a particular index, all other elements falling in and after that index must be shifted right (their indices are incremented by 1) When deleting from a particular index, all other elements falling in and after that index must be shifted left to fill the newly opened space (index decremented by 1) • ArrayLists automatically shift memory for insertion and deletion. • For both Array and ArrayList the index is used primarily for looping or as a result of a search for a particular element.

30. What can ArrayLists hold? • ArrayLists can hold any object! • Every class implicitly extends Object • every object “is an” Object • methods of Object you can usefully redefine: • booleanequals(Object obj): check for equality • String toString(): returns object’s “state” as string; could be used to print all instance variables’ values • void finalize(): used in garbage collection • Upside: ArrayLists store things as Object, so maximum polymorphic flexibility • since everything is an Object, ArrayLists can hold instances of any and every class • adding/removing anything from an ArrayList is easy • Downside: ArrayListsonly store Objects • only methods we can use on retrieved objects are those few trivial ones of Object itself: equals, toString, and finalize • want to store only objects of a particular type AND have the compiler do type-checking for that type

31. Generics! • Generics allow us to write a collection class A to hold instances of another class B, without regard for what that class B is public ArrayList<ElementType> () • Developers use “generics” to implement a collection class without knowing what specific type of object the user of that collection will want to store • example: Java’s ArrayList’s class file defines an array list of ElementTypesleft unspecified, but when users of the ArrayList actually declare and instantiate one, the type must be fully specified (e.g., an ArrayList of Lannisters to serve Joffrey), much the way arrays need types • Java replaces ElementTypewithLannistersinreturntypes and parameters of any ArrayListmethod you want to use • but you must keep the literal < > brackets wherever they are used to indicate use of generics! • Generics allow for generality of using any type while still having compiler do type checking • Think of the “generic” as a specialization of the type ArrayList.

32. java.util.ArraryListMethods (1/2) // Note: only most important methods are shown; // see JavaDocs for full class // Note: literal use of < and > // one of the many constructors for ArrayList // class – specialize it by providing ElementType, // much as Array has the type it stores. // think of <> as “of” public ArrayList<ElementType>() // returns an object of type ElementType public ElementTypeget(int index) // inserts the specified element at the // specified position in this ArrayList // note the parameters! public void add(int index, ElementTypeelement) // inserts specified element at end of ArrayList public boolean add(ElementTypeelement) // removes the ElementType at given index public ElementTyperemove(int index) // returns number of elements stored inArrayList public int size() // returns true if the ArrayList contains zero // elements; false otherwise public booleanisEmpty() NOTE: ElementTypecan be any class you want!

33. java.util.ArrayListMethods (2/2) • ArrayListsalso have methods which access elements by searching (as opposed to using an index) • these methods take a parameter of type Object (superclass from which all Java classes inherit) • But you should never pass in (or get back) anything except an ElementType – using polymorphism here not for generality but to get compile-time type checking // finds first occurrence of specified elementpublic intindexOf(Object elem) // return true if ArrayList contains specified // elementpublic boolean contains(Object elem) // remove first occurrence of specified element public boolean remove(Object elem) • Some other ArrayList notes… • can add object at particular slot or at end • can retrieve an object stored at a particular index and perform operations on it • can use for loop to access all objects in ArrayList • shifting elements in memory for adding / deleting from an ArrayList is done automagically by Java!

34. Summary of ArrayLists • More flexible than arrays for insertion/deletion • dynamically shifting elements and adjusting size in response to insert/delete done automagically • Full class with useful methods, e.g., • get(intindex), add(ElementTypeelement), • add(intindex, ElementTypeelement), • indexOf(ElementTypeelem) //search • remove(int index), size(), isEmpty(), • Can hold a heterogeneous collection of any kind of Object; want homogeneous collections… • So specialize the ArrayList type by adding a “generic” specification to a declaration or instantiation, thereby specifying two classes in one statement: the collection and the type of object it is to hold and return • implementer of ArrayListcollection declares constructor with <ElementType>as placeholder public ArrayList<ElementType>() • user of ArrayList “fills in” ElementType private ArrayList<Lannister>_lannisters; _lannisters= new ArrayList<Lannister>(); • Be sure to use literal < > for specialized type!

35. Example (1/4) public class LannisterCollection { /* To declare ArrayList, must specify type of * object ArrayListstores. Replace all * occurrences of ElementType with Lannister, * including where ElementTypeoccurs in literal * <> brackets. Could extend ArrayList, but * it goes against good design. */ // ArrayList declaration private ArrayList<Lannister>_lannisters; public LannisterCollection() { // ArrayList initialization – note literal <> _lannisters= new ArrayList<Lannister>(); for(inti = 0; i < 5; i++){ // Add a Lannister at every pass _lannisters.add(new Lannister()); } } // Adds a new Lannister at the end public void addLannister(Lannisterlannister){ _lannisters.add(lannister); } // If the specified Lannister is in the // collection, remove and banishes him/her public void banishLannister(Lannisterlannister){ if (_lannisters.contains(lannister) { _lannisters.remove(lannister); } } } // end of class

36. Example (2/4) • <Lannister> indicates use of Java generics • now, only Lannisterinstances can be stored and retrieved from this ArrayList • In LannisterCollection’s constructor, adding a new Lannisterworks: _lannisters.add(new Lannister()); • However, adding another type to the ArrayList of Lannisters won’t work: _lannisters.add(new String(“Yeah!”)); // Won’t work... parameter needs to be // of type Lannister • Exception thrown! • “The methodadd(Lannister)in the typeArrayList<Lannister>is not applicable for the arguments (String)”

37. Example (3/4) // Class that models all that Joffrey does public class Joffrey { private LannisterCollection _lannisterCollec; private Lannister _betrayer; public Joffrey(LannisterCollection lannisters, Lannister betrayer) { // store associations _lannisterCollec= lannisters; _betrayer = betrayer; } // Method to act like the true king of // Westeros - uses only one Lannister public void actKingly(Lannisterlannister){ this.issueDecree(); //method def elided lannister.obey(this); //method def elided this.stormOutInASnit(); //method def elided } // Method to destroy anyone who might betray // Joffrey; uses LannisterCollection to banish public void banishBetrayer(){ this.stormIn(); // method definition elided _lannisterCollec.banishLannister(_betrayer); } // other methods elided } // end of class

38. Example (4/4) /* Top level class * Creates a set of Lannistersand plays out the * deleted scenes of the Game of Thrones TV show */ public class GameofThronesTVShow { private LannisterCollection _lannisters; public GameofThronesTVShow() { _lannisters = new LannisterCollection(); Lannistertyrion = new Lannister(“Tyrion”); _lannisters.add(tyrion); Joffreyjoffrey = new Joffrey(_lannisters, tyrion); // Day 1: A boring day joffrey.beMeanToSansa(); joffrey.whineAndComplain(); // Day 2: A more exciting day Lannistercersei = new Lannister(“Cersei”); joffrey.actKingly(cersei); joffrey.banishBetrayer(); // Rest of the TV show elided } // Other methods elided } // End of class

39. Enhanced forLoop • Remember forloops from last lecture? • Basic for loop was extended in Java 5 to make iteration over arrays and other collections easier • commonly called for-each or for-inloop • <> here are NOT literal, i.e., not for generics for (<type> <var>: <structure>) { <loop body> } • <type>: class of objects stored in the <structure> • <var>: name of the loop counter • <structure>: data structure (array or collection) you’d like to iterate over • Intended to simplify most common form of iteration, when, as name suggests, loop body is applied to each and every member of the collection. • But, how do for-eachloop and for loop differ? • in a for loop, have access to index at which an item is stored in an array or collection (and hence item itself) • in a for-each loop, we don’t have direct access to the index, but can easily access item (see next slide example).

40. for-each vs. forloop • Consider this for loop: // Somewhere in the LannisterCollection class // note: _lannisters is an ArrayList<Lannister> for (inti = 0, i < _lannisters.size(); i++) { if (i % 2 == 0) { // if index ‘i’ is even // burnInHell() is defined in Lannister _lannisters.get(i).burnInHell(); } } • In the loop above, we only want to call burnInHell() on elements at even indices. A for-eachloop would not be appropriate in this case. Why? Because we don’t execute burnInHell()on every element in the ArrayList; we only care about elements at specific indices. • However, if we want to operate on every element in the ArrayList and the loop body does not require element indices, we may use a for-each loop: // Instead of only destroying even-numbered // Lannisters, now kill every one! for (Lannisterlan: _lannisters) { // notice how don’t need to use index // to get Lannister from ArrayList lan.burnInHell(); } • A great advantage of for-each loops is that they don’t give you ArrayIndexOutOfBoundsExceptions! Why? • Java does the indexing for you. And Java is never wrong!

41. Understanding Mainline (and optional params) package Demos.Mainline; // Dummy class to understand Mainline public class App { public App() { … } // Standard mainline function public static void main(String[] argv) { System.out.println(argv[0]); System.out.println(argv[1]); new App(); } } • If we type this in a shell: java Demos.Mainline.App Hello CS15 • We get output: Hello CS15 • In this example, if we did not pass two or more parameters to the mainline, we’d get an ArrayIndexOutOfBoundsException! • Why? Because argv’s size is exactly equal to the number of parameters passed to the mainline! • You won’t need to use mainline parameters in CS15, but we wanted you to know they exist. You will probably use them in CS32!

42. Announcements • Cartoon is early handin today at 11:59pm! On time deadline is Saturday, October 19, 2013, at 10:00pm. Late handin is Monday, October 21, 2013. • Did we mention that the best Cartoons will be framed in eternal glory?! Do something awesome with your Cartoon! • Remember to complete Lab 5 (Debugging) this week.