CS1101: Programming Methodology

Slides:



Advertisements
Similar presentations
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Arrays.
Advertisements

Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
Array Basics Suppose you need to process daily temperatures for a 12-month period in a science project, would you use 365 variables? You can, but would.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Arrays Sections 1-4.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
Multidimensional arrays Many problems require information be organized as a two- dimensional or multidimensional list Examples –Matrices –Graphical animation.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 2D Arrays.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 10 Arrays.
Chapter 10 Arrays. Topics Declaring and instantiating arrays Array element access Arrays of objects Arrays as method parameters Arrays as return values.
Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection.
بسم الله الرحمن الرحيم CPCS203: Programming II. Objectives After you have read and studied this chapter, you should be able to –Manipulate a collection.
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.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
CS180 Recitation 25th/26th October, 2007 Department of Computer Science, Purdue University.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 10 *Arrays with more than one dimension *Java Collections API.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Arrays.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Arrays Lists.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 10 Arrays and Collections.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
1 CS100J 25 October 2006 Arrays. Reading: Secs 8.1, 8.2, 8.3. Listen to the following lectures on loops on your Plive CD. They are only 2-3 minutes long,
Chapter 10 2D Arrays Collection Classes. Topics Arrays with more than one dimension Java Collections API ArrayList Map.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
CS1101: Programming Methodology Aaron Tan.
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.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Arrays : Objectives After you have read and studied this chapter, you should be able to –Manipulate a collection of data values, using an array. –Declare.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Array Basics An array is a collection of data.
Java Script: Arrays (Chapter 11 in [2]). 2 Outline Introduction Introduction Arrays Arrays Declaring and Allocating Arrays Declaring and Allocating Arrays.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
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.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
1 On (computational) simplicity We are trying to teach not just Java, but how to think about problem solving. Computer science has its field called computational.
CS1101: Programming Methodology
Primitive Arrays A primitive array stores multiple values of the same primitive data type. rainfall The index of the first position in an.
1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Arrays and ArrayList Files Most of these slides.
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.
Arrays. Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional  Java.
Arrays. Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional  Java.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
CS1101: Programming Methodology Recitation 5 – Arrays and Collections.
Arrays Chapter 6. Objectives learn about arrays and how to use them in Java programs learn how to use array parameters and how to define methods that.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
CS1101: Programming Methodology
CS 180 Recitation 7 Arrays. Used to store similar values or objects. An array is an indexed collection of data values of the same type. Arrays are the.
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,
Arrays (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Arrays (adapted from the publisher’s.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Arrays Collections of data Winter 2004CS-1010 Dr. Mark L. Hornick 1.
1 CS Oct 2008 Arrays. Reading: Secs 8.1, 8.2, 8.3 Listen to the following lectures on loops on your Plive CD. They are only 2-3 minutes long, and.
1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Arrays and ArrayList Most of these slides are.
Data Structures & Algorithms CHAPTER 2 Arrays Ms. Manal Al-Asmari.
Chapter VII: Arrays.
Chapter 10 Arrays Animated Version
Basic Files + (Chapter 10 – Arrays) : Objectives
Chapter 6: Arrays.
Chapter 10 Arrays ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Chapter 6: Arrays.
Arrays and Collections
Object Oriented Programming in java
Chapter 9 Array Basics Suppose you need to process daily temperatures for a 12-month period in a science project, would you use 365 variables? You can,
Arrays.
Presentation transcript:

CS1101: Programming Methodology

2 CS1101X: Lecture #10 Lecture 10: Arrays Acknowledgement: Thomas Wu. After you have read and studied this chapter, you should be able to  Manipulate a collection of data values, using an array.  Declare and use an array of primitive data types in writing a program.  Declare and use an array of objects in writing a program  Define a method that accepts an array as its parameter and a method that returns an array  Describe how a two-dimensional array is implemented as an array of arrays  Manipulate a collection of objects, using lists

3 CS1101X: Lecture #10 Array Basics An array is a collection of data values. If your program needs to deal with 100 integers, 500 Account objects, 365 real numbers, etc., you will use an array. In Java, an array is an indexed collection of data values of the same type.

4 CS1101X: Lecture #10 Arrays of Primitive Data Types Array Declaration [ ] // variation 1 [ ]// variation 2 Array Creation = new [ ] Example double[ ] rainfall; rainfall = new double[12]; Variation 1 double rainfall [ ]; rainfall = new double[12]; Variation 2 An array is like an object!

5 CS1101X: Lecture #10 Accessing Individual Elements Individual elements in an array accessed with the indexed expression. double[] rainfall = new double[12]; The index of the first position in an array is 0. rainfall rainfall[2] This indexed expression refers to the element at position #2

6 CS1101X: Lecture #10 Motivation (1/3) Task: Find the minimum value of 3 integers int min; if ((value1<=value2) && (value1<=value3)) min = value1; else if ((value2<=value1) && (value2<=value3)) min = value2; else if ((value3<=value1) && (value3<=value2)) min = value3; What if the list is big?  Code will be longer – the logical expression in each ‘if’ statement will be longer and more complex.

7 CS1101X: Lecture #10 Motivation (2/3) Consider this algorithm int min = value1; if (value2 < min) min = value2; if (value3 < min) min = value3; What if the list is big?  Code will still be longer, but if we make use of the regular pattern and the array structure for the data, we can ‘roll’ the if statements into a loop.

8 CS1101X: Lecture #10 Motivation (3/3) Using the array structure int min = value[0]; if (value[1] < min) min = value[1]; if (value[2] < min) min = value[2]; Rolling into a loop using array subscript/index int min = value[0]; for (int k = 1; k < 3; ++k) { if (value[k] < min) min = value[k]; } The above code can be modified easily for a bigger list.

9 CS1101X: Lecture #10 Basic Terminology An array is a form of ordered list. A list is composed of elements. Elements in a list have a common name. The list as a whole is referenced through the common name. List is homogeneous, that is, list elements are of the same type — the base type. Elements of a list are referenced by subscripting (indexing) the common name.

10 CS1101X: Lecture #10 Java Array Features Subscripts are denoted as expressions within square brackets: [ ] Base (element) type can be any type Size of array can be specified at run time Index type is integer and the index range must be 0... n-1, where n is the number of elements Automatic bounds checking  Ensures any reference to an array element is valid Data field length specifies the number of elements in the list Array is an object  Has features common to all other objects

11 CS1101X: Lecture #10 Example (1/2) Definitions char[] c; int[] value = new int[10]; String[] s = new String[2]; Causes  Array object variable c is un-initialized.  Array object variable v references a new 10-element list of integers. Each of the integers is by default initialized to 0.  Array object variable s references a new 2-element list of strings. Each of the strings is by default initialized to null. c - value s null

12 CS1101X: Lecture #10 Example (2/2) For simplicity, sometimes we represent simply as value

13 CS1101X: Lecture #10 Array Processing – Sample 1 double[] rainfall = new double[12]; doubleannualAverage, sum = 0.0; for (int i = 0; i < rainfall.length; i++) { rainfall[i] = Double.parseDouble( JOptionPane.showinputDialog(null, "Rainfall for month " + (i+1) ) ); sum += rainfall[i]; } annualAverage = sum / rainfall.length; The public constant length returns the capacity of an array.

14 CS1101X: Lecture #10 Array Processing – Sample 2 double[] rainfall = new double[12]; String[] monthName = new String[12]; monthName[0] = "January"; monthName[1] = "February"; … double annualAverage, sum = 0.0; for (int i = 0; i < rainfall.length; i++) { rainfall[i] = Double.parseDouble( JOptionPane.showinputDialog(null, "Rainfall for " + monthName[i] )); sum += rainfall[i]; } annualAverage = sum / rainfall.length; The same pattern for the remaining ten months. The actual month name instead of a number.

15 CS1101X: Lecture #10 Array Processing – Sample 3 Compute the average rainfall for each quarter. //assume rainfall is declared and initialized properly double[] quarterAverage = new double[4]; for (int i = 0; i < 4; i++) { sum = 0; for (int j = 0; j < 3; j++) { // compute the sum of sum += rainfall[3*i + j]; // one quarter } quarterAverage[i] = sum / 3.0; // Quarter (i+1) average }

16 CS1101X: Lecture #10 Array Initialization (1/2) Like other data types, it is possible to declare and initialize an array at the same time. int[] number = { 2, 4, 6, 8 }; double[] samplingData = { 2.443, 8.99, 12.3, , 18.2, 9.00, 3.123, , }; String[] monthName = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; number.length samplingData.length monthName.length

17 CS1101X: Lecture #10 Array Initialization (2/2) int[] number = { 2, 4, 6, 8 }; is equivalent to int[] number = new int[4]; number[0] = 2; number[1] = 4; number[2] = 6; number[3] = 8; Member length  A public final data field called length.  Size of the array.

18 CS1101X: Lecture #10 Coin Change Problem (1/2) Rewrite the code for coin change problem (Lecture #0, slide 56), using an array int coins[6] = { 100, 50, 20, 10, 5, 1 }; Without array: int amt = scanner.nextInt(); int numberOfCoins = 0; numberOfCoins += amt/100; amt %= 100; numberOfCoins += amt/50; amt %= 50; numberOfCoins += amt/20; amt %= 20; numberOfCoins += amt/10; amt %= 10; numberOfCoins += amt/5; amt %= 5; numberOfCoins += amt/1; amt %= 1;

19 CS1101X: Lecture #10 Coin Change Problem (2/2) With array: int amt = scanner.nextInt(); int numberOfCoins = 0; int coins[] = { 100, 50, 20, 10, 5, 1 }; for (int i = 0; i < 6; i++) { numberOfCoins += amt/coins[i]; amt %= coins[i]; }

20 CS1101X: Lecture #10 Index Out Of Bounds Code int[] b = new int[100]; b[-1] = 123; b[100] = 9; Causes  Array variable to reference a new list of 100 integers Each element is initialized to 0  Two exceptions to be thrown -1 is not a valid index – too small 100 is not a valid index – too large  IndexOutOfBoundsException

21 CS1101X: Lecture #10 Variable-size Declaration In Java, we are not limited to fixed-size array declaration. The following code prompts the user for the size of an array and declares an array of designated size: int size; int[] number; size = Integer.parseInt(JOptionPane.showInputDialog(null, "Size of an array:")); number = new int[size];

22 CS1101X: Lecture #10 Arrays of Objects In Java, in addition to arrays of primitive data types, we can declare arrays of objects An array of primitive data is a powerful tool, but an array of objects is even more powerful. The use of an array of objects allows us to model the application more cleanly and logically.

23 CS1101X: Lecture #10 Method main() (1/2) Usual signature for method main public static void main(String[] args)  args is an array of String objects. Consider public class Demo { public static void main(String[] args) { for (int i = 0; i < args.length; ++i) { System.out.println("args[" + i + "]: " + args[i]); }

24 CS1101X: Lecture #10 Method main() (2/2) This allows user to specify command line arguments when executing the program. java Demo 10 ABC-D Hello "Ice Cream" Output args[0]: 10 args[1]: ABC-D args[2]: Hello args[3]: Ice Cream

25 CS1101X: Lecture #10 The Person Class We will use Person objects to illustrate the use of an array of objects. Person latte; latte = new Person( ); latte.setName("Ms. Latte"); latte.setAge(20); latte.setGender('F'); System.out.println( "Name: " + latte.getName() ); System.out.println( "Age : " + latte.getAge() ); System.out.println( "Sex : " + latte.getGender() ); The Person class supports the set methods and get methods.

26 CS1101X: Lecture #10 Creating an Object Array (1/3) Code State of Memory Person[ ] person; person = new Person[20]; person[0] = new Person( ); A A Only the name person is declared, no array is allocated yet. After is executed A A person

27 CS1101X: Lecture #10 Creating an Object Array (2/3) person Code State of Memory Person[ ] person; person = new Person[20]; person[0] = new Person( ); B B Now the array for storing 20 Person objects is created, but the Person objects themselves are not yet created. After is executed B B person

28 CS1101X: Lecture #10 Creating an Object Array (3/3) Code State of Memory Person[ ] person; person = new Person[20]; person[0] = new Person( ); C C One Person object is created and the reference to this object is placed in position person person After is executed C C Person

29 CS1101X: Lecture #10 Person Array Processing – Sample 1 Create Person objects and set up the person array. String name, inpStr; intage; chargender; for (int i = 0; i < person.length; i++) { name = inputBox.getString( "Enter name:" ); // read in data values age= inputBox.getInteger( "Enter age:" ); inpStr= inputBox.getString( "Enter gender:" ); gender = inpStr.charAt(0); person[i] = new Person( ); // create a new Person and assign values person[i].setName(name); person[i].setAge(age); person[i].setGender(gender); }

30 CS1101X: Lecture #10 Person Array Processing – Sample 2 Find the youngest and oldest persons. intminIdx = 0;// index to the youngest person intmaxIdx = 0; // index to the oldest person for (int i = 1; i < person.length; i++) { if ( person[i].getAge() < person[minIdx].getAge() ) { minIdx = i; // found a younger person } else if (person[i].getAge() > person[maxIdx].getAge() ) { maxIdx = i; // found an older person } // person[minIdx] is the youngest and person[maxIdx] is the oldest

31 CS1101X: Lecture #10 Object Deletion – Approach 1 int delIdx = 1; person[delIdx] = null; Delete Person B by setting the reference in position 1 to null person A A B B C C D D A A 0123 A A C C D D Before is executed A A After is executed A A

32 CS1101X: Lecture #10 Object Deletion – Approach 2 int delIdx = 1, last = 3; person[delIndex] = person[last]; person[last--] = null; Delete Person B by setting the reference in position 1 to the last person person A A B B C C D D A A 0123 A A C C D D Before is executed A A After is executed A A

33 CS1101X: Lecture #10 Person Array Processing – Sample 3 Searching for a particular person. Approach 2 Deletion is used. int i = 0; while ( person[i] != null && !person[i].getName().equals("Latte") ) { i++; } if ( person[i] == null ) { // not found - unsuccessful search System.out.println("Ms. Latte was not in the array"); } else { // found - successful search System.out.println("Found Ms. Latte at position " + i); }

34 CS1101X: Lecture #10 Passing Arrays to Methods (1/6) How do we write a method that accepts an array as its parameter, and how do we invoke such a method? The method to sum the values in an integer list: public static int sumList(int[] list) { int sum = 0; for (int i = 0; i < list.length; ++i) { sum += list[i]; } return sum; }

35 CS1101X: Lecture #10 Passing Arrays to Methods (2/6) The invocation of the sumList() method: public static void main(String[] args) { int[] aList = { 2, 6, 4 }; int answer = sumList(aList); System.out.println("Sum of list is " + answer); } Output: Sum of list is 12

36 CS1101X: Lecture #10 Passing Arrays to Methods (3/6) Code State of Memory minOne = searchMinimum(arrayOne); public int searchMinimum(float[] number)) { … } A A At before searchMinimum A A arrayOne A. A. Local variable number does not exist before the method execution

37 CS1101X: Lecture #10 Passing Arrays to Methods (4/6) Code State of Memory minOne = searchMinimum(arrayOne); public int searchMinimum(float[] number)) { … } arrayOne B B The address is copied at B B number B. B. The value of the argument, which is an address, is copied to the parameter.

38 CS1101X: Lecture #10 Passing Arrays to Methods (5/6) arrayOne number While at inside the method C C Code State of Memory minOne = searchMinimum(arrayOne); public int searchMinimum(float[] number)) { … } C C C. C. The array is accessed via number inside the method.

39 CS1101X: Lecture #10 Passing Arrays to Methods (6/6) arrayOne At after searchMinimum D D number Code State of Memory minOne = searchMinimum(arrayOne); public int searchMinimum(float[] number)) { … } D D D. D. The parameter is erased. The argument still points to the same object. arrayOne At after searchMinimum D D

40 CS1101X: Lecture #10 Passing Array Elements to Methods (1/2) How do we write a method that accepts an array element as its parameter, and how do we invoke such a method? The method to sum two values in an integer list: public static int sumTwoElements(int a, int b) { return a + b; }  No difference from a method that adds two integer values.

41 CS1101X: Lecture #10 Passing Array Elements to Methods (2/2) The invocation of the sumTwoElements() method: public static void main(String[] args) { int[] aList = { 2, 6, 4 }; int answer = sumTwoElements(aList[0], aList[2]); System.out.println("Sum is " + answer); } Output: Sum is 6

42 CS1101X: Lecture #10 Two-Dimensional Arrays Two-dimensional arrays are useful in representing tabular information.

43 CS1101X: Lecture #10 Declaring and Creating a 2D Array Declaration [][] //variation 1 [][] //variation 2 Creation = new [ ][ ] Example double[][] payScaleTable; payScaleTable = new double[4][5]; payScaleTable

44 CS1101X: Lecture #10 Accessing an Element An element in a two-dimensional array is accessed by its row and column index.

45 CS1101X: Lecture #10 Sample 2D Array Processing double[ ] average = { 0.0, 0.0, 0.0, 0.0 }; for (int i = 0; i < payScaleTable.length; i++) { for (int j = 0; j < payScaleTable[i].length; j++) { average[i] += payScaleTable[i][j]; } average[i] = average[i] / payScaleTable[i].length; } Find the average of each row.

46 CS1101X: Lecture #10 Java Implementation of 2D Arrays The sample array creation payScaleTable = new double[4][5]; is really a shorthand for payScaleTable = new double [4][ ]; payScaleTable[0] = new double [5]; payScaleTable[1] = new double [5]; payScaleTable[2] = new double [5]; payScaleTable[3] = new double [5];

47 CS1101X: Lecture #10 Two-Dimensional Arrays Subarrays may be different lengths. Executing triangularArray = new double[4][ ]; for (int i = 0; i < 4; i++) triangularArray[i] = new double [i + 1]; results in an array that looks like:

48 CS1101X: Lecture #10 Example #1 (1/2) Segment int[][] m = new int[3][]; m[0] = new int[4]; m[1] = new int[4]; m[2] = new int[4]; Produces m m[0] m[1] m[2] m[0][0] m[0][1] m[0][2] m[0][3]m[1][0] m[1][1] m[1][2] m[1][3] m[2][0] m[2][1] m[2][2] m[2][3]

49 CS1101X: Lecture #10 Example #1 (2/2) Segment for (int r = 0; r < m.length; ++r) { for (int c = 0; c < m[r].length; ++c) { System.out.print("Enter a value: "); m[r][c] = scanner.nextInt(); } What does this code do?

50 CS1101X: Lecture #10 Example #2 Segment String[][] s = new String[4][]; s[0] = new String[2]; s[1] = new String[2]; s[2] = new String[4]; s[3] = new String[3] Produces s s[0] s[1] s[2] s[3] null s[0][0] s[0][1]s[1][0] s[1][1] null s[2][0] s[2][1] s[2][2] s[2][3] s[3][0] s[3][1] s[3][2]

51 CS1101X: Lecture #10 Example #3 Segment int[][] c = { {1, 2}, {8, 9}, {3, 8}, {12, 1, 7} }; Produces c c[0] c[1] c[2] c[3] c[0][0] c[0][1]c[1][0] c[1][1] 1217 s[2][0] s[2][1] c[3][0] c[3][1] c[3][2]

52 CS1101X: Lecture #10 Methods with Multi-dimensional Arrays Method zero() sets to 0 all of the elements of the subarrays of its int[][] parameter array a. public void zero(int[][] a) { for (int r = 0; r < a.length; ++r) for (int c = 0; c < a[r].length; ++c) a[r][c] = 0; }

53 CS1101X: Lecture #10 Matrices A two-dimensional array is sometimes known as a matrix because it resembles that mathematical concept. A matrix a with m rows and n columns is represented mathematically in the following manner.

54 CS1101X: Lecture #10 Matrix Addition (1/2) Definition C = A + B  c i,j = a i,j + b i,j

55 CS1101X: Lecture #10 Matrix Addition (2/2) public static double[][] add(double[][] a, double[][] b) { // determine number of rows in solution int m = a.length; // determine number of columns in solution int n = a[0].length; // create the array to hold the sum double[][] c = new double[m][n]; // compute the matrix sum row by row for (int i = 0; i < m; ++i) { // produce the current row for (int j = 0; j < n; ++j) { c[i][j] = a[i][j] + b[i][j]; } return c; }

56 CS1101X: Lecture #10 Matrix Multiplication Definition C = A * B  c i,j = (a i,1  b 1,j ) + (a i,2  b 2,j ) (a i,n  b n,j )  c i,j is sum of terms produced by multiplying the elements of A’s row i with B’s column j.

57 CS1101X: Lecture #10 List The java.util standard package contains different types of classes for maintaining a collection of objects. These classes are collectively referred to as the Java Collection Framework (JCF). JCF includes classes that maintain collections of objects as sets, lists, or maps.

58 CS1101X: Lecture #10 Java Interface A Java interface defines only the behavior of objects  It includes only public methods with no method bodies.  It does not include any data members except public constants  No instances of a Java interface can be created

59 CS1101X: Lecture #10 Collections Framework Limitations of arrays  Cannot be resized  There are no operations that support insertion of new elements or deletion of existing elements. Collections framework  A rich set of list representations and algorithms.  Interface is java.util.AbstractCollection.

60 CS1101X: Lecture #10 JCF Lists JCF includes the List interface that supports methods to maintain a collection of objects as a linear list L = (l 0, l 1, l 2,..., l N ) We can add to, remove from, and retrieve objects in a given list. A list does not have a set limit to the number of objects we can add to it.

61 CS1101X: Lecture #10 List Methods Here are five of the 25 list methods: boolean add ( Object o ) Adds an object o to the list void clear ( ) Clears this list, i.e., make the list empty Object get ( int idx ) Returns the element at position idx boolean remove ( int idx ) Removes the element at position idx int size ( ) Returns the number of elements in the list

62 CS1101X: Lecture #10 Using Lists To use a list in a program, we must create an instance of a class that implements the List interface. Two classes that implement the List interface:  ArrayList  LinkedList The ArrayList class uses an array to manage data. The LinkedList class uses a technique called linked-node representation.

63 CS1101X: Lecture #10 Sample List Usage Here's an example of manipulating a list: import java.util.*; List friends; Person person; friends = new ArrayList( ); person = new Person("jane", 10, 'F'); friends.add( person ); person = new Person("jack", 6, 'M'); friends.add( person ); Person p = (Person) friends.get( 1 );

64 CS1101X: Lecture #10 Class ArrayList (1/5) ArrayList provides a resizeable list representation that implements the List interface. ArrayList c = new ArrayList(); ArrayList d = new ArrayList(20);  Variable c references a new ArrayList that can represent up to 10 elements before it will need to update its internal capacity.  Variable d can represent up to 20 elements before it will need to update its capacity. Refer to API specification.

65 CS1101X: Lecture #10 Class ArrayList (2/5) Adding elements: c.add("Brooklyn"); c.add("Wichita Falls"); c ArrayList "Brooklyn""Wichita Fall"

66 CS1101X: Lecture #10 Class ArrayList (3/5) Adding elements: for (int i = 0; i < 3; ++i) { d.add(new Integer(i)); } d ArrayList 0 Integer 1 2

67 CS1101X: Lecture #10 Class ArrayList (4/5) Method get() to access elements of an ArrayList. public static void displayList(ArrayList a) { for (int i = 0; i < a.size(); ++i) System.out.println(a.get(i)); } Invocation (assuming that class is DemoArrayList): DemoArrayList.displayList(c); Output: Brooklyn Witchita Falls

68 CS1101X: Lecture #10 Class ArrayList (5/5) Method set() to change the value of an element in an ArrayList. c.set(1, "Glen Rock"); DemoArrayList.displayList(c); Output: Brooklyn Glen Rock

69 CS1101X: Lecture #10 Iterator (1/2) A very common process is examining every element in a collection. The ArrayList class provides a special way to iterate over its elements.  The iterator() method of ArrayList returns an Iterator object.  Iterator interface is defined in the java.util package.  Need to import java.util.Iterator. Methods provided in Iterator:  boolean hasNext() Returns whether this Collection has more elements to return.  Object next() Returns next element of this Collection. If there is no next element, it throws a NoSuchElementException.  void remove() Remove from this Collection the last element returned by the iterator.

70 CS1101X: Lecture #10 Iterator (2/2) import java.util.ArrayList; import java.util.Iterator; public class DemoList { public static void main(String[] args) { ArrayList list = new ArrayList (); list.add(new Integer(12)); list.add(new Integer(7)); list.add(new Integer(-98)); for (int i = 0; i < list.size(); ++i) { System.out.println(list.get(i)); } Iterator it = list.iterator(); while (it.hasNext()) { System.out.println(it.next()); } Same output:

71 CS1101X: Lecture #10 Collections Algorithms (1/3) A collection of algorithms for performing standard list operations.  Algorithms are implemented as class methods of the class java.util.Collections.  Several methods make use of interfaces java.lang.Comparable or java.util.Comparator.  public int compareTo(Object v) Returns a negative value if this object is less than v; returns zero if the two objects are equal; and returns a positive value otherwise.  public int compare(Object v1, Object v2) Returns a negative value if v1 is less than v2; returns zero if the two values are equal; and returns a positive value otherwise.  public boolean equals(Object v) Returns true or false, whether v is equal to this object.

72 CS1101X: Lecture #10 Collections Algorithms (2/3) import java.util.*; public class DemoCollections { public static void main(String[] args) { ArrayList a = new ArrayList (); for (int i = 0; i < 10; ++i) a.add(new Integer(i)); System.out.println("Original: " + a); Collections.reverse(a); System.out.println("Reversed: " + a); Collections.shuffle(a); System.out.println("Shuffled: " + a); Collections.sort(a); System.out.println("Sorted: " + a); }

73 CS1101X: Lecture #10 Collections Algorithms (3/3) Original: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Reversed: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] Shuffled: [3, 0, 1, 9, 5, 2, 8, 6, 7, 4] Sorted: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Output:

74 CS1101X: Lecture #10 End of Lecture #10