Chapter 8 - Arrays.

Slides:



Advertisements
Similar presentations
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. It is common to use two nested loops when filling or searching: for.
Advertisements

Week 10 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Arrays, part 2. Array applications Arrays are useful whenever a relatively large amount of data must be kept available in memory for processing We will.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Arrays Sections 1-4.
Arrays.
Chapter 7 – 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.
Datalogi A 8: 27/10. Array Array: Sequence of values of the same type Construct array: new double[10] Store in variable of type double[] double[] data.
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Arrays Lists.
For each primitive type there is a wrapper class for storing values of that type: Double d = new Double(29.95); Wrapper Classes Wrapper objects can be.
Chapter 9: Advanced Array Concepts
Week 10 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all.
Arrays and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member in.
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.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
1 Arrays An array is a collection of data values, all of which have the same type. The size of the array is fixed at creation. To refer to specific values.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
Aug 9, CMSC 202 ArrayList. Aug 9, What’s an Array List ArrayList is  a class in the standard Java libraries that can hold any type of object.
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 and Array Lists CS 21a. Problem 1: Reversing Input Problem: Read in three numbers and then print out the numbers in reverse order Straightforward.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Common Elementary Algorithms Some of the basic but frequently used algorithms for manipulating arrays. These algorithms are so important that: a)Some programming.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Arrays Chapter 7.
CMSC 202 ArrayList Aug 9, 2007.
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
Chapter VII: Arrays.
Chapter 10 Arrays Animated Version
Principles of Computer Science I
Chapter 8 – Arrays and Array Lists
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Chapter 7: Working with Arrays
Computer Programming BCT 1113
7.6 Common Array Algorithm: Filling
JavaScript: Functions.
Basic Files + (Chapter 10 – Arrays) : Objectives
Arrays, For loop While loop Do while loop
Chapter 6: Arrays.
Chapter 6 Arrays Solution Opening Problem
7 Arrays.
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.
Chapter 10 Arrays ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
© A+ Computer Science - Arrays and Lists © A+ Computer Science -
CMSC 202 ArrayList Aug 9, 2007.
int [] scores = new int [10];
Chapter 6: Arrays.
Object Oriented Programming in java
CMSC 202 ArrayList Aug 9, 2007.
int [] scores = new int [10];
Arrays and Array Lists CS 21a.
Announcements Lab 6 was due today Lab 7 assigned this Friday
7 Arrays.
Dr. Sampath Jayarathna Cal Poly Pomona
Suggested self-checks: Section 7.11 #1-11
Data Structures & Algorithms
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,
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
How do you do the following?
Arrays.
Presentation transcript:

Chapter 8 - Arrays

Chapter Goals Learn arrays ArrayLists will be left out, learn in 367 along with auto-boxing Wrapper classes Multi-dimensional arrays

Arrays Common to want to deal with collection of items Keep information about all 302 students Information about all video files on computer All of my grades since kindergarten Books in a library Infeasible to enumerate an identifier for each book1, book2, book3, …., book500

Arrays Arrays are a sequence of spots to store a certain data type Two components Data Type Size

Data Type What type of element do we want to store in our array? Can be a primitive or reference type Syntax: <datatype>[] <identifier>; <dataype> <identifier>[];

Arrays Problem: Want to display differences in scores from average We have to keep track of each score We could just create one identifier for all 10 scores (score1, score2…) But what if we wanted to take in more scores? Solution: Use an array of scores to store all scores

Arrays double[] scores; OR double scores[];

Size To create an array, we must use the new operator Syntax: <identifier> = new <datatype>[<size>]; Examples: scores = new double[10]; double[] scores = new double[10]; What data type is an array?

Memory Diagram scores 0 1 2 3 4 5 6 7 8 9

Arrays Can access an individual item in the collection Use a single identifier for the whole collection (scores) and then use an indexed expression to access an array element Zero based indexing! (just like Strings) Index numbered 0 through <size>-1 scores[0] //1st element scores[2] //3rd element Can use expressions like scores[i+1]

Memory Diagram scores 0 1 2 3 4 5 6 7 8 9 scores[2]

Example double[] scores = new double[10]; double avg, sum = 0; for(int i=0; i < 10; i++){ System.out.print(“Enter Score”); scores[i] = in.nextDouble(); sum += scores[i]; } avg = sum/10; System.out.print("Score " + i + " "); System.out.print(score[i] + " "); System.out.println(score[i] – avg);

Sample Run Enter score: 22 Enter score: 24 Enter score: 90

Initial Values When array is created, all values are initialized depending on array type: Numbers: 0 Boolean: false Object References: null Means compiler does not force initialization like with primitives

Length We assumed size of array was 10…what if we aren’t sure? Or want to change size? Every array has a public constant data member named length (no parenthesis) for(int i=0; i < scores.length; i++){ System.out.print("Score "+i+" "); System.out.print(score[i]+" "); System.out.println(score[i] – avg); }

Example double[] rainfall = new double[12]; double avg, sum = 0; for(int i=0; i < rainfall.length; i++){ rainfall[i] = getDouble("Enter monthly rainfall for month "+i); sum += rainfall[i]; } avg = sum/12; System.out.print(“Month "+i+" "); System.out.print(rainfall[i]+" "); System.out.println(rainfall[i] – avg);

Modifications What if we want to output specific month? Can keep array of Strings String[] monthName = new String[12]; monthName[0] = “Jan”; monthName[1] = “Feb”; monthName[2] = “Mar”; monthName[3] = “Apr”; monthName[4] = “May”; monthName[5] = “Jun”; monthName[6] = “Jul”; monthName[7] = “Aug”; monthName[8] = “Sep”; monthName[9] = “Oct”; monthName[10] = “Nov”; monthName[11] = “Dec”;

Example double[] rainfall = new double[12]; double avg, sum = 0; for(int i=0; i < rainfall.length; i++){ rainfall[i] = getDouble("Enter monthly rainfall for month "+monthName[i]); sum += rainfall[i]; } avg = sum/12; System.out.print(“Month "+monthName[i]+" "); System.out.print(rainfall[i]+" "); System.out.println(rainfall[i] – avg);

Initializing Arrays You can also initialize all values right off the bat instead of individually as before String[] monthName = {“Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”, “Jul”, “Aug”, “Sep”, “Oct”, “Nov”, “Dec”}; No need to use new, or specify size Knows size from number of values in list

Array Sizes So far, we have used constants to define the size of the array Fixed-size array declaration What about if we aren’t sure how many scores we want? Soln 1 – declare array of size 100 and get input, quitting once the array is full

Array Sizes 2 problems Inefficient – wastes space (what if we get 1 score? Wasted space for other 99) underutilization Limiting – what if we want more than 100 scores? Solution – variable size array – non-constant values for size Note: You still cannot change the size once created (length is constant)

Array Sizes int size; double [] scores; System.out.println("Enter number of scores to enter: "); size = in.nextInt(); scores = new double[size];

Array Sizes Can use any mathematic expression Must give a whole number (integer)

Arrays of Objects What’s wrong? BankAccount[] ba; System.out.print(“Enter number of accounts: “); int numAccounts = in.nextInt(); ba = new BankAccount[numAccounts]; ba[0].deposit(500); What’s wrong?

Arrays of Objects We have created the array (i.e. the bins) What’s in the bins? We still need to create an object for each bin

Memory Diagram ba 0 1 2 3 4 5 6 7 8 9 …

Arrays of Objects Each “bin” (index of the array) is a reference When we declare an array, we declare numAccounts identifiers in essence Now we need to create a BankAccount object for each bin

Arrays of Objects BankAccount[] ba; System.out.print(“Enter number of accounts: “); int numAccounts = in.nextInt(); ba = new BankAccount[numAccounts]; ba[0] = new BankAccount(); ba[0].deposit(500);

Memory Diagram ba 0 1 2 3 4 5 6 7 8 9 … :BankAccount balance 500

Arrays of Objects We will use the Person class to illustrate this concept. An array of objects is declared and created just as an array of primitive data types is. Person[] person; person = new Person[20];

Arrays of Objects An array of Person objects after the array is created.

Arrays of Objects The person array with one Person object added to it.

Arrays of Objects To assign data values to this object, we can execute person[0].setName (“Ms. Latte”); person[0].setAge (20); person[0].setGender (‘F’); The syntax here is the one used to call an object’s method; we are using an indexed expression to refer to the object instead of a simple variable.

Example The following program illustrates various aspects of array processing: Creating a new Person array. Creating a new Person object and assigning values to it. Finding the average age of the persons in the array. Finding the youngest and oldest persons in the array. Finding a particular person in the array.

/* Sample Program: Illustrate the processing of an array of Person objects File: ProcessPersonArray.java */ public class ProcessPersonArray { public static void main (String[] args) { Person[] person; //declare the person array person = new Person[5]; //and then create it

//----------- Create person Array ------------// String name, inpStr; int age; char gender; for (int i = 0; i < person.length; i++) { //read in data values name = in.nextLine(); age = in.nextInt(); inpStr = in.next().charAt(0); //create a new Person and assign values person[i] = new Person( ); person[i].setName ( name ); person[i].setAge ( age ); person[i].setGender( gender ); }

//------ Compute Average Age --------------// float sum = 0, averageAge; for (int i = 0; i < person.length; i++) { sum += person[i].getAge(); } averageAge = sum / (float) person.length; System.out.println("Average age: " + averageAge); //-- Find the youngest and oldest person ------// //-- Approach No. 3: Using person reference ---// Person youngest, //points to the youngest person oldest; //points to the oldest person youngest = oldest = person[0];

for (int i = 1; i < person.length; i++) { if ( person[i].getAge() < youngest.getAge() ) { //found a younger person youngest = person[i]; } else if (person[i].getAge() > oldest.getAge() ) { //found an older person oldest = person[i]; System.out.println("Oldest : " + oldest.getName() + " is " + oldest.getAge() + " years old."); System.out.println("Youngest: " + youngest.getName() + " is " + youngest.getAge() + " years old.");

Example An array of Person objects with two Person variables.

Deleting Objects How do we delete an object? tms[x] = null; Remember garbage collection takes any objects no longer being referenced to (i.e. can never be accessed again)

Wrapper Classes

Wrapper Classes Allow us to treat primitives as objects Each wrapper class has a primitive data member

Wrapper Classes

Finding the Average double[] scores = ... //Get scores from user double avg = 0; for(int i = 0; i < scores.length; i++){ avg += scores[i]; } avg = avg / scores.length;

Counting double[] scores = ...//Get scores from user double avg = 0; for(int i = 0; i < scores.length; i++){ avg += scores[i]; } avg = avg / scores.length; // Count number of scores greater than average int count = 0; if(scores[i] >= avg){ count++;

Finding a Value double[] scores = ...//Get scores from file double search = ...//Get value to search from user boolean found = false; for(int j = 0; j < scores.length; j++) { if(Math.abs(scores[j],search) <= 1E-14) found = true; }

Maximum/Minimum double max = scores[0]; double min = scores[0]; for(int i = 1; i < scores.length; i++) { if(scores[i] > max) max = scores[i]; } else if(scores[i] < min) min = scores[i];

Counting Using Objects public class Bank { private BankAccount[] accounts; public int count(double atLeast) { int matches = 0; for (int j = 0; j < accounts.length; j++) { if (accounts[j].getBalance() >= atLeast) matches++; // Found a match } return matches; } . . . }

Searching Using Objects public class Bank { public BankAccount find(int accountNumber) { for (int j = 0; j < accounts.length; j++) { if (accounts[j].getAccountNumber() == accountNumber) // Found a match return accounts[j]; } return null; // No match in the array list } }

Maximum Using Objects public BankAccount maximum() { if (accounts.length == 0) return null; BankAccount largestYet = accounts[0]; for (int i = 1; i < accounts.length; i++) { BankAccount a = accounts[i]; if (a.getBalance() > largestYet.getBalance()) largestYet = a; } return largestYet; }

Multi-Dimensional Arrays So far we've seen only one-dimensional arrays Many problems may require us to represent data in a “table” format, in two dimensions We use two-dimensional arrays in order to do this What do we need to add?

2D Arrays Instead of one index, we need two indices – row and column Example: We have multiple students, and each student has multiple scores – row for student, column for test int[][] scores; scores = new int[numStudents][numTests];

2D Arrays Suppose we want a 2D array that stores a pay scale. It would be declared as: double[][] payScaleTable; or double payScaleTable[][]; and created by payScaleTable = new double[4][5];

2D Arrays Accessing an element of a two-dimensional array.

2D Arrays Arrays are a specific structure Two dimensional arrays do not have to be tables!!! They are an array of arrays How do you check number of rows? Columns? Use the length instance field

payScaleTable = new double[4][5]; 2D Arrays The sample array creation payScaleTable = new double[4][5]; is a shorthand for payScaleTable = new double [4][ ]; payScaleTable[0] = new double [5]; payScaleTable[1] = new double [5]; payScaleTable[2] = new double [5]; and so on.

Executing the statements on the left in sequence will create the array of arrays shown on the right.

2D Arrays The expression payScaleTable.length refers to the length of the payScaleTable array itself.

payScaleTable[1].length 2D Arrays The expression payScaleTable[1].length refers to the length of the array stored at index 1 of payScaleTable.

Questions How can we declare a symmetrical table, where we only specify half the values? In other words, [0][1] == [1][0] How do we represent a cube? How do you “traverse”, or go through the elements of an multi-dimensional array?

Copying Arrays Arrays are reference variables, so we treat them like other objects Copying an array variable yields a second reference to the same array double[] data = new double[10]; // fill array . . . double[] prices = data;

Cloning Use clone to make true copy double[] prices = (double[]) data.clone(); // Note: clone returns an object, so we // type cast

Cloning

Copying Elements System.arraycopy() not encouraged Hard to manipulate Using for loops is more powerful

Copying certain elements How do I copy count positions from array from to array to, starting at positions fromStart and toStart respectively?

Copying Certain Elements Answer: Use for loops! for(int i = 0; i < count; i++) { to[toStart + i] = from[fromStart + i]; }

Inserting a Value To insert, we'll make a new array, copy over the elements with the new element inserted // insert x in position i int[] newData = new int[data.length+1]; // <loop to copy elements before i> newData[i] = x; // <loop to copy elements after i> data = newData; // set data to new version

Deleting a Value Deleting is similar: Make a new copy without the old element // Remove position i int[] newData = new int[data.length-1]; // <loop to copy elements before i> // <loop to copy elements after i> data = newData;

Growing Arrays If the array is full and you need more space, you can grow the array Can't simply expand – need to create new array Create a new, larger array. double[] newData = new double[2*data.length]; Copy all elements into the new array Store the reference to the new array in the array variable data = newData;

Passing Arrays to Methods Exactly the same as objects, the reference is passed to method parameters Same thing if returning an array Remember that if you change an object in a method, the change affects others who use that object

Passing Arrays to Methods public int searchMinimum(double[] number) { int indexOfMinimum = 0; for (int i = 1; i < number.length; i++){ if (number[i] < number[indexOfMinimum]) { //found a smaller element indexOfMinimum = i; } return indexOfMinimum; To call this method (from a method of the same class), we write

Passing Arrays to Methods double[] arrayOne; //create and assign values to arrayOne ... //get the index of the smallest element of arrayOne int minOne = searchMinimum(arrayOne); //output the result System.out.print(“Minimum value in Array One is ”); System.out.print(arrayOne[minOne] + “at position ” + minOne);

Passing Arrays to Methods length is especially important in methods, since we have no other way of knowing the size (except by sending another parameter) When returning an array, we can store it in a reference variable: double[] scores = getDoubles(“Enter 10 scores”);

Passing Arrays to Methods Passing an array to a method means we are passing a reference to an array.

Example: Candy in a Machine Declare a 2D array of double values named machine that represents the price of each candy item in a given row and column of a candy machine. double [] [] machine = new double[10][5]; ©2001 Deb Deppeler. All rights reserved.

Example: Candy in a Machine .50 .75 .45 .60 .85 .90 .80 .55 .70 .65 .40 .95 1.10 .30 .35 Create the 2D array with 3 rows and 5 columns. Assign prices to each item. machine[r][c] = ?? r=0 1 2 double [] [] machine = new double[3][5]; machine[0][0] = 0.50; machine[0][1] = 0.75; machine[0][2] = 0.45; machine[0][3] = 0.60; machine[0][4] = 0.85; machine[1][0] = 0.90; machine[1][1] = 0.80; machine[1][2] = 0.55; machine[1][3] = 0.70; machine[1][4] = 0.65; machine[2][0] = 0.40; machine[2][1] = 0.95; machine[2][2] = 1.10; machine[2][3] = 0.30; machine[2][4] = 0.35; ©2001 Deb Deppeler. All rights reserved.

Example: Candy in a Machine Can we use initializer lists for multi-dimensional arrays. Only at time of declaration. double [][] machine = { { 0.50, 0.90, 0.40 }, { 0.75, 0.80, 0.95 }, { 0.45, 0.55, 1.10 }, { 0.60, 0.70, 0.30 }, { 0.85, 0.65, 0.35 } } ; double [] [] machine = new double[3][5]; machine[0][0] = 0.50; machine[0][1] = 0.75; machine[0][2] = 0.45; machine[0][3] = 0.60; machine[0][4] = 0.85; machine[1][0] = 0.90; machine[1][1] = 0.80; machine[1][2] = 0.55; machine[1][3] = 0.70; machine[1][4] = 0.65; machine[2][0] = 0.40; machine[2][1] = 0.95; machine[2][2] = 1.10; machine[2][3] = 0.30; machine[2][4] = 0.35; ©2001 Deb Deppeler. All rights reserved.

Example: Candy in a Machine Write a code fragment to increase the price of all items by 5 cents. for ( int i=0; i < machine.length; i++ ) for ( int j=0; j < machine[i].length; j++ ) machine[i][j] = machine[i][j] + 0.05; double [] [] candyPrice = new double[10][5]; write a code fragment to increase the price of all candy items by 5 cents. ©2001 Deb Deppeler. All rights reserved.