Chapter 7 – 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.
Chapter 7: Arrays and Array Lists. To become familiar with using arrays and array lists To learn about wrapper classes, auto-boxing and the generalized.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Seven: Arrays and Array Lists.
Chapter 13 ARRAY LISTS AND ARRAYS. CHAPTER GOALS To become familiar with using array lists to collect objects To learn about common array algorithms To.
Chapter 7 Arrays and Array Lists. Chapter Goals To become familiar with using arrays and array lists To learn about wrapper classes, auto-boxing and the.
Chapter 13 ARRAY LISTS AND ARRAYS CHAPTER GOALS –To become familiar with using array lists to collect objects –To learn about common array algorithms –To.
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-1: Arrays reading: 7.1 self-checks: #1-9 videos: Ch. 7 #4.
Computer Science A 10: 20/3. Array Array: Sequence of values of the same type Construct array: new double[10] Store in variable of type double[] double[]
Chapter 7  Arrays and Array Lists 1 Chapter 7 Arrays and Array Lists.
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.
C++ for Engineers and Scientists Third Edition
ARRAYS AND ARRAYLISTS Chapter 7. Array  Sequence of values of the same type  Primitive types  Objects  Create an Array  double[] values = new double[10]
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Java Programming Week 6: Array and ArrayList Chapter 7.
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.
Week 9-10 – Arrays and Array Lists Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
ICOM 4015: Advanced Programming Lecture 7 Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Reading: Chapter Seven:
Chapter Goals To collect elements using arrays and array lists
Week 10 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
ARRAYLIST Collections of Data. ArrayLists Array lists can grow and shrink as needed ArrayList is a generic class (similar to C++ template) ArrayList has.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
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.
© 2007 Lawrenceville Press Slide 1 Chapter 10 Arrays  Can store many of the same kind of data together  Allows a collection of related values to be stored.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Chapter 8: Collections: Arrays. 2 Objectives One-Dimensional Arrays Array Initialization The Arrays Class: Searching and Sorting Arrays as Arguments The.
When constructing a two-dimensional array, specify how many rows and columns are needed: final int ROWS = 3; final int COLUMNS = 3; String[][] board =
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 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.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Lecture Notes – Classes and Objects (Ch 7-8) Yonglei Tao.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
Fall 2006Slides adapted from Java Concepts companion slides1 Arrays and Array Lists Advanced Programming ICOM 4015 Lecture 7 Reading: Java Concepts Chapter.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
Arrays…JavaCPython have fixed lengthyes*yesno are initialized to default values yesno? track their own lengthyesnoyes trying to access “out of bounds”
Chapter 7 – Arrays and Array Lists Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Chapter 6 – Arrays and Array Lists Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Copyright © 2013 by John Wiley & Sons. All rights reserved. ARRAYS and ARRAYLISTS CHAPTER Slides by Donald W. Smith TechNeTrain.com 6 Final Draft 10/30/2011.
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
Array length = maximum number of elements in array Usually, array is partially filled Need companion variable to keep track of current size Uniform naming.
Arrays. Array: Sequence of values of the same type Construct array: Store in variable of type double[ ] new double[10] double[] data = new double[10];
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 7 – Arrays and Array Lists Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. 1.
Two Dimensional Arrays Found in chapter 8, Section 8.9.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
int [] scores = new int [10];
When constructing a two-dimensional array, specify how many rows and columns are needed: final int ROWS = 3; final int COLUMNS = 3; String[][] board =
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Array: Sequence of values of the same type Construct array: new double[10] Store in variable of type double[] : double[] data = new double[10]; When array.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Chapter 9 Introduction to Arrays Fundamentals of Java.
Chapter 7 – Arrays and Array Lists Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
A 2-D Array is a structure that storage space both vertically and horizontally. Thus, the array has both rows and columns. 2-D Arrays are used to create.
Arrays Chapter 7.
Chapter 7 – Arrays and Array Lists
Array Lists An array list stores a sequence of values whose size can change. An array list can grow and shrink as needed. ArrayList class supplies methods.
Principles of Computer Science I
Chapter 7 – Arrays and Array Lists
Chapter 8 – Arrays and Array Lists
Chapter 7 – Arrays.
7.6 Common Array Algorithm: Filling
Lecture Notes – Arrays and ArrayLists (Ch 7-8)
Introduction to Computer Science and Object-Oriented Programming
Building Java Programs Chapter 7
ARRAYS & ARRAY LISTS.
Presentation transcript:

Chapter 7 – Arrays

Array: Sequence of values of the same type Construct array: new double[10] Store in variable of type double[]: double[] data = new double[10]; When array is created, all values are initialized depending on array type: Numbers: 0 Boolean: false Object References: null

Arrays

Use [] to access an element: Arrays Use [] to access an element: values[2] = 29.95;

Using the value stored: Arrays Using the value stored: System.out.println("The value of this data item is " + values[2]); Get array length as values.length (Not a method!) Index values range from 0 to length - 1 Accessing a nonexistent element results in a bounds error: double[] values = new double[10]; values[10] = 29.95; // ERROR Limitation: Arrays have fixed length

Declaring Arrays

Syntax 7.1 Arrays

Question? What elements does the data array contain after the following statements? double[] values = new double[10]; for (int i = 0; i < values.length; i++) values[i] = i * i;

Question? What do the following program segments print? Or, if there is an error, describe the error and specify whether it is detected at compile-time or at run-time. double[] a = new double[10]; System.out.println(a[0]); double[] b = new double[10]; System.out.println(b[10]); double[] c; System.out.println(c[0]);

Make Parallel Arrays into Arrays of Objects   Make Parallel Arrays into Arrays of Objects // Don't do this int[] accountNumbers; double[] balances;

Make Parallel Arrays into Arrays of Objects Avoid parallel arrays by changing them into arrays of objects: BankAccount[] accounts;         

Wrapper Classes For each primitive type there is a wrapper class for storing values of that type: Double d = new Double(29.95); Wrapper objects can be used anywhere that objects are required instead of primitive type values:   ArrayList<Double> values= new ArrayList<Double>(); data.add(29.95); double x = data.get(0);

Wrappers There are wrapper classes for all eight primitive types:

Auto-boxing even works inside arithmetic expressions: Means: Auto-boxing: Automatic conversion between primitive types and the corresponding wrapper classes: Double d = 29.95; // auto-boxing; same as // Double d = new Double(29.95); double x = d; // auto-unboxing; same as // double x = d.doubleValue(); Auto-boxing even works inside arithmetic expressions: d = d + 1; Means: auto-unbox d into a double add 1 auto-box the result into a new Double store a reference to the newly created wrapper object in d

Auto-boxing and Array Lists To collect numbers in an array list, use the wrapper type as the type parameter, and then rely on auto-boxing: ArrayList<Double> values = new ArrayList<Double>(); values.add(29.95); double x = values.get(0); Storing wrapped numbers is quite inefficient Acceptable if you only collect a few numbers Use arrays for long sequences of numbers or characters

Traverses all elements of a collection: The Enhanced for Loop Traverses all elements of a collection: double[] values = ...; double sum = 0; for (double element : values) { sum = sum + element; } Read the loop as “for each element in values” Traditional alternative: for (int i = 0; i < values.length; i++) double element = values[i];

Works for ArrayLists too: The Enhanced for Loop Works for ArrayLists too: ArrayList<BankAccount> accounts = ...; double sum = 0; for (BankAccount account : accounts) { sum = sum + aaccount.getBalance(); } Equivalent to the following ordinary for loop: for (int i = 0; i < accounts.size(); i++) BankAccount account = accounts.get(i); sum = sum + account.getBalance();

Must use an ordinary for loop: The Enhanced for Loop The “for each loop” does not allow you to modify the contents of an array: for (double element : values) { element = 0; // ERROR—this assignment does not // modify array element } Must use an ordinary for loop: for (int i = 0; i < values.length; i++) values[i] = 0; // OK

Syntax 7.3 The “for each” Loop

Common Array Algorithm: Filling Fill an array with zeroes: for (int i = 0; i < values.length; i++) { values[i] = 0; } Fill an array list with zeroes: for (int i = 0; i < values.size(); i++) values.set(i, 0);

Common Array Algorithm Find a value Find the maximum Counting

Common Array Algorithm: Computing Sum and Average To compute the sum of all elements, keep a running total: double total = 0; for (double element : values) { total = total + element; } To obtain the average, divide by the number of elements: double average = total /values.size(); Be sure to check that the size is not zero

Animation 7.1: Removing from an Array for (int i = pos; i < valueSize-1; i++) { values[i] = values[i+1]; } valueSize--;

Common Array Algorithm: Inserting an Element Array list ⇒ use method add Unordered array ⇒ Insert the element as the last element of the array Increment the variable tracking the size of the array if (valuesSize < values.length) { values[valuesSize] = newElement; valuesSize++; }

Common Array Algorithm: Inserting an Element Ordered array ⇒ Start at the end of the array, move that element to a higher index, then move the one before that, and so on until you finally get to the insertion location Insert the element Increment the variable tracking the size of the array if (valuesSize < values.length) { for (int i = valuesSize; i > pos; i--) values[i] = values[i - 1]; } values[pos] = newElement; valuesSize++;

Common Array Algorithm: Inserting an Element

Common Array Algorithm: Locating the Position of an Element Problem: Locate the position of an element so that you can replace or remove it Use a variation of the linear search algorithm, but remember the position instead of the matching element Example: Locate the position of the first element that is larger than 100: int pos = 0; boolean found = false; while (pos < values.size() && !found) { if (values.get(pos) > 100) { found = true; } else { pos++; } } if (found) { System.out.println("Position: " + pos); } else { System.out.println("Not found"); }

Common Array Algorithm: Copying an Array Copying an array variable yields a second reference to the same array: double[] values = new double[6]; . . . // Fill array double[] prices = values;

Common Array Algorithm: Copying an Array To make a true copy of an array, call the Arrays.copyOf method: double[] prices = Arrays.copyOf(values, values.length);

Common Array Algorithm: Copying an Array To grow an array that has run out of space, use the Arrays.copyOf method: values = Arrays.copyOf(values, 2 * values.length);

Common Array Algorithm: Growing an Array Example: Read an arbitrarily long sequence numbers into an array, without running out of space: int valuesSize = 0; while (in.hasNextDouble()) { if (valuesSize == values.length) values = Arrays.copyOf(values, 2 * values.length); values[valuesSize] = in.nextDouble(); valuesSize++; }

Common Array Algorithm: Printing Element Separators When you display the elements of an array or array list, you usually want to separate them: Ann | Bob | Cindy When you display the elements of an array or array list, you usually want to separate them Print the separator before each element except the initial one (with index 0): for (int i = 0; i < names.size(); i++) { if (i > 0) System.out.print(" | "); } System.out.print(names.get(i));

Two-Dimensional Arrays When constructing a two-dimensional array, specify how many rows and columns are needed: final int ROWS = 3; final int COLUMNS = 3; String[][] board = new String[ROWS][COLUMNS]; Access elements with an index pair: board[1][1] = "x"; board[2][1] = "o";

Traversing Two-Dimensional Arrays It is common to use two nested loops when filling or searching: for (int i = 0; i < ROWS; i++) for (int j = 0; j < COLUMNS; j++) board[i][j] = " ";

Traversing Two-Dimensional Arrays You can also recover the array dimensions from the array variable: board.length is the number of rows board[0].length is the number of columns Rewrite the loop for filling the tic-tac-toe board: for (int i = 0; i < board.length; i++) for (int j = 0; j < board[0].length; j++) board[i][j] = " ";

ch07/twodim/TicTacToe.java Continued 1 /** 1 /** 2 A 3 x 3 tic-tac-toe board. 3 */ 4 public class TicTacToe 5 { 6 private String[][] board; 7 private static final int ROWS = 3; 8 private static final int COLUMNS = 3; 9 10 /** 11 Constructs an empty board. 12 */ 13 public TicTacToe() 14 { 15 board = new String[ROWS][COLUMNS]; 16 // Fill with spaces 17 for (int i = 0; i < ROWS; i++) 18 for (int j = 0; j < COLUMNS; j++) 19 board[i][j] = " "; 20 } 21 Continued

ch07/twodim/TicTacToe.java (cont.) 22 /** 23 Sets a field in the board. The field must be unoccupied. 24 @param i the row index 25 @param j the column index 26 @param player the player ("x" or "o") 27 */ 28 public void set(int i, int j, String player) 29 { 30 if (board[i][j].equals(" ")) 31 board[i][j] = player; 32 } 33 Continued

ch07/twodim/TicTacToe.java (cont.) 35 Creates a string representation of the board, such as 36 |x o| 37 | x | 38 | o| 39 @return the string representation 40 */ 41 public String toString() 42 { 43 String r = ""; 44 for (int i = 0; i < ROWS; i++) 45 { 46 r = r + "|"; 47 for (int j = 0; j < COLUMNS; j++) 48 r = r + board[i][j]; 49 r = r + "|\n"; 50 } 51 return r; 52 } 53 }

ch07/twodim/TicTacToeRunner.java Continued 1 import java.util.Scanner; 2 3 /** 4 This program runs a TicTacToe game. It prompts the 5 user to set positions on the board and prints out the 6 result. 7 */ 8 public class TicTacToeRunner 9 { 10 public static void main(String[] args) 11 { 12 Scanner in = new Scanner(System.in); 13 String player = "x"; 14 TicTacToe game = new TicTacToe(); Continued

ch07/twodim/TicTacToeRunner.java (cont.) 15 boolean done = false; 16 while (!done) 17 { 18 System.out.print(game.toString()); 19 System.out.print( 20 "Row for " + player + " (-1 to exit): "); 21 int row = in.nextInt(); 22 if (row < 0) done = true; 23 else 24 { 25 System.out.print("Column for " + player + ": "); 26 int column = in.nextInt(); 27 game.set(row, column, player); 28 if (player.equals("x")) 29 player = "o"; 30 else 31 player = "x"; 32 } 33 } 34 } 35 }

ch07/twodim/TicTacToeRunner.java (cont.) Program Run: | | Row for x (-1 to exit): 1 Column for x: 2 | x | Row for o (-1 to exit): 0 Column for o: 0 |o | | x| Row for x (-1 to exit): -1