Chapter 8 – Arrays and Array Lists

Slides:



Advertisements
Similar presentations
Arrays and ArrayLists Ananda Gunawardena. Introduction Array is a useful and powerful aggregate data structure presence in modern programming languages.
Advertisements

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.
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.
Chapter 7 – Arrays.
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.
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.
Chapter 6 Iteration.  Executes a block of code repeatedly  A condition controls how often the loop is executed while (condition) statement  Most commonly,
Chapter 6: Iteration Part 2. Create triangle pattern [] [][] [][][] [][][][] Loop through rows for (int i = 1; i
ICOM 4015: Advanced Programming Lecture 7 Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Reading: Chapter Seven:
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.
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.
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.
AP Comp Sci A Chapter 12 - Arrays. Ch 12 Goals: Goals: Declare and create arrays Declare and create arrays Access elements in arrays Access elements in.
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 =
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors.
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.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
October 28, 2015ICS102: For Loop1 The for-loop and Nested loops.
Arrays Construct array: new double[10] Store in variable of type double[] double[] data = new double[10];
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.
Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!
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.
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
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];
Chapter 7 – Arrays and Array Lists Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. 1.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
When constructing a two-dimensional array, specify how many rows and columns are needed: final int ROWS = 3; final int COLUMNS = 3; String[][] board =
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
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.
Chapter 7 Iteration. Chapter Goals To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To.
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.
Test 2 Review Outline.
CSC111 Quick Revision.
Chapter 7 User-Defined Methods.
Principles of Computer Science I
Chapter 7 – Arrays and Array Lists
Chapter 7 – Arrays.
[ 4.00 ] [ Today’s Date ] [ Instructor Name ]
7.6 Common Array Algorithm: Filling
Chapter 7 Part 1 Edited by JJ Shepherd
Chapter 6 More Conditionals and Loops
Multi-dimensional Array
Counted Loops.
Selected Topics From Chapter 6 Iteration
An Introduction to Java – Part I, language basics
Can store many of the same kind of data together
python.reset() Also moving to a more reasonable room (CSE 403)
OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS
How do you do the following?
Presentation transcript:

Chapter 8 – Arrays and Array Lists The Plan For Today Chapter 8 Project Chapter 8 8.6: Two-Dimensional Arrays 8.7: Copying Arrays Ch8 Work Time Upcoming Quiz: Ch.8 – Thurs. 1/29

Syntax 8.3: The "for each" Loop  for (Type variable : collection) statement Example:  for (double e : data) sum = sum + e; Purpose: To execute a loop for each element in the collection. In each iteration, the variable is assigned the next element of the collection. Then the statement is executed.

Two-Dimensional Arrays When constructing a two-dimensional array, you specify how many rows and columns you need: You access elements with an index pair a[i][j] final int ROWS = 3; final int COLUMNS = 3; String[][] board = new String[ROWS][COLUMNS]; board[i][j] = "x";

A Tic-Tac-Toe Board Figure 6: A Tic-Tac-Toe Board

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] = " ";

File TicTacToe.java (p.299) 01: /** 02: A 3 x 3 tic-tac-toe board. 03: */ 04: public class TicTacToe 05: { 06: /** 07: Constructs an empty board. 08: */ 09: public TicTacToe() 10: { 11: board = new String[ROWS][COLUMNS]; 12: // Fill with spaces 13: for (int i = 0; i < ROWS; i++) 14: for (int j = 0; j < COLUMNS; j++) 15: board[i][j] = " "; 16: } 17: Continued…

File TicTacToe.java 18: /** 18: /** 19: Sets a field in the board. The field must be unoccupied. 20: @param i the row index 21: @param j the column index 22: @param player the player ("x" or "o") 23: */ 24: public void set(int i, int j, String player) 25: { 26: if (board[i][j].equals(" ")) 27: board[i][j] = player; 28: } 29: 30: /** 31: Creates a string representation of the board, such as 32: |x o| 33: | x | 34: | o| 35: @return the string representation 36: */ Continued…

File TicTacToe.java 37: public String toString() 38: { 38: { 39: String r = ""; 40: for (int i = 0; i < ROWS; i++) 41: { 42: r = r + "|"; 43: for (int j = 0; j < COLUMNS; j++) 44: r = r + board[i][j]; 45: r = r + "|\n"; 46: } 47: return r; 48: } 49: 50: private String[][] board; 51: private static final int ROWS = 3; 52: private static final int COLUMNS = 3; 53: }

File TicTacToeTester.java (p.300) 01: import java.util.Scanner; 02: 03: /** 04: This program tests the TicTacToe class by prompting the 05: user to set positions on the board and printing out the 06: result. 07: */ 08: public class TicTacToeTester 09: { 10: public static void main(String[] args) 11: { 12: Scanner in = new Scanner(System.in); 13: String player = "x"; 14: TicTacToe game = new TicTacToe(); 15: boolean done = false; 16: while (!done) 17: { Continued…

File TicTacToeTester.java 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: } Continued…

Output | | | | | | Row for x (-1 to exit): 1 Column for x: 2 | | | x| | | | x| | Row for o (-1 to exit): 0 Column for o: 0 |o | Row for x (-1 to exit): -1

Self Check 11. How do you declare and initialize a 4-by-4 array of integers? 12. How do you count the number of spaces in the tic-tac-toe board? int[][] array = new int[4][4]; int count = 0; for (int i = 0; i < ROWS; i++) for (int j = 0; j < COLUMNS; j++) if (board[i][j] == ' ') count++;

Copying Arrays: Copying Array References Copying an array variable yields a second reference to the same array double[] data = new double[10]; // fill array . . . double[] prices = data;

Copying Arrays: Cloning Arrays Use clone to make true copy double[] prices = (double[]) data.clone();

Copying Arrays: Copying Array Elements System.arraycopy(from, fromStart, to, toStart, count);

Adding an Element to an Array System.arraycopy(data, i, data, i + 1, data.length - i - 1); data[i] = x;

Removing an Element from an Array System.arraycopy(data, i + 1, data, i, data.length - i - 1);

Growing an Array If the array is full and you need more space, you can grow the array: Create a new, larger array. Copy all elements into the new array Store the reference to the new array in the array variable double[] newData = new double[2 * data.length]; System.arraycopy(data, 0, newData, 0, data.length); data = newData;

Growing an Array Figure 12: Growing an Array

Self Check 13. How do you add or remove elements in the middle of an array list? Use the insert and remove methods. 14. Why do we double the length of the array when it has run out of space rather than increasing it by one element? Allocating a new array and copying the elements is time- consuming. You wouldn't want to go through the process every time you add an element.

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

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

Partially Filled Arrays Array length = maximum number of elements in array Usually, array is partially filled Need companion variable to keep track of current size Uniform naming convention: Update dataSize as array is filled: final int DATA_LENGTH = 100; double[] data = new double[DATA_LENGTH]; int dataSize = 0; data[dataSize] = x; dataSize++;

Partially Filled Arrays Figure 15: A Partially Filled Array

An Early Internet Worm Figure 16: A "Buffer Overrun" Attack

Work Time – Remember… Username: apcs Password: apcs15 Always Save in Your Folder on C: drive Keep up the great conversation and working together! Make use of example code in textbook Read, read, read! Make sure you understand code you write. Thanks for leaving the lab looking great!