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.

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.
Chapter 13 Array Lists and Arrays. 2 ArrayList Basics Definition: An array list is a sequence of objects Construct an array List object, i.e. in the Purse.java.
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 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.
Interfaces and Polymorphism Lesson - 8. Objectives Interfaces Supertype and subtype references Polymorphism Inner classes.
Chapter 5 Arrays and Vectors An array allows you to group data items together in a structure that is processed via an index. They allow you to process.
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[]
CSM-Java Programming-I Spring,2005 Class Design Lesson - 4.
More loops Horstmann Ch 7 continued.. The do-loop continue- condition ? loop-body statements next statement false true WHILE-LOOP continue- condition?
Chapter 6 Iteration Goals To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To understand.
Chapter 7  Arrays and Array Lists 1 Chapter 7 Arrays and Array Lists.
Chapter 9 Interfaces and Polymorphism. Chapter Goals To learn about interfaces To be able to convert between class and interface references To understand.
Arrays CSC 171 FALL 2002 LECTURE 20. Arrays Suppose we want to write a program that reads a set of test grades and prints them, marking the highest grade?
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.
ARRAYS AND ARRAYLISTS Chapter 7. Array  Sequence of values of the same type  Primitive types  Objects  Create an Array  double[] values = new double[10]
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
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
Chapter 3 Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To recognize the limitations of the int and double types.
Week 10 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Chapter 6 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.
ArrayList, Multidimensional Arrays
CHAPTER 18 SORTING AND SEARCHING. CHAPTER GOALS To study the several searching and sorting algorithms To appreciate that algorithms for the same task.
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
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 of Objects 1 Fall 2012 CS2302: Programming Principles.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
IMPLEMENTING ARRAYLIST – Part 2 COMP 103. RECAP  Abstract Classes – overview, details in 2 nd year  Implementing the ArrayList: size(), get(), set()
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
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.
Stacks and Queues. 2 3 Runtime Efficiency efficiency: measure of computing resources used by code. can be relative to speed (time), memory (space), etc.
Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!
Arrays…JavaCPython have fixed lengthyes*yesno are initialized to default values yesno? track their own lengthyesnoyes trying to access “out of bounds”
CHAPTER 9 INTERFACES AND POLYMORPHISM Chapter Goals: –To learn about interfaces –To be able to convert between supertype and subtype references –To understand.
Chapter 14 Exception Handling. Chapter Goals To learn how to throw exceptions To be able to design your own exception classes To understand the difference.
CHAPTER 9 INTERFACES AND POLYMORPHISM. CHAPTER GOALS To learn about interfaces To be able to convert between supertype and subtype references To understand.
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.
1 Intro to Computer Science Arrays Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj, Isaiah, Allison, Thibault University of.
Chapter 6 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.
Programmeren 1 6 september 2010 HOORCOLLEGE 2: INTERACTIE EN CONDITIES PROGRAMMEREN 1 6 SEPTEMBER 2009 Software Systems - Programming - Week.
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.
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 =
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
Chapter 9 Introduction to Arrays Fundamentals of Java.
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.
Principles of Computer Science I
Chapter 8 – Arrays and Array Lists
[ 4.00 ] [ Today’s Date ] [ Instructor Name ]
7.6 Common Array Algorithm: Filling
ARRAYS & ARRAY LISTS.
Chapter 7 Iteration.
int [] scores = new int [10];
Presentation transcript:

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 be able to use arrays To understand when to choose array lists and arrays in your programs To implement partially filled arrays To learn how to use two-dimensional arrays

Array Lists Consider Purse class Purse doesn't remember individual Coin objects, just the total Don't know how many coins--can't have variables coin1...coin10 Use ArrayList to store variable number of objects ArrayList coins = new ArrayList(); coins.add(new Coin(0.1, "dime"));... size method yields number of elements

Retrieving Array List Elements Use get method Index starts at 0 Must cast to correct type Coin c = coins.get(0); // gets first coin Bounds error if index is out of range Most common bounds error: int n = coins.size(); c = (Coin)coins.get(n); // ERROR // legal index values are 0...n-1

Stepping Through all Elements for (int i = 0; i < coins.size(); i++) { Coin c = (Coin)coins.get(i); do something with c }

Adding and Removing Elements set overwrites an existing value coins.set(4, aNickel); add adds a new value before the index add(i, c)

remove removes an element at an index

File Purse.java 1 import java.util.ArrayList; 2 3 /** 4 A purse holds a collection of coins. 5 */ 6 public class Purse 7 { 8 /** 9 Constructs an empty purse. 10 */ 11 public Purse() 12 { 13 coins = new ArrayList(); 14 } /** 17 Add a coin to the purse.

aCoin the coin to add 19 */ 20 public void add(Coin aCoin) 21 { 22 coins.add(aCoin); 23 } /** 26 Get the total value of the coins in the purse. the sum of all coin values 28 */ 29 public double getTotal() 30 { 31 double total = 0; 32 for (int i = 0; i < coins.size(); i++) 33 { 34 Coin aCoin = (Coin)coins.get(i); 35 total = total + aCoin.getValue(); 36 } 37 return total;

38 } private ArrayList coins; 41 } 42

Linear Search Algorithm public class Purse { public boolean find(Coin aCoin) { for (int i = 0; i < coins.size(); i++) { Coin c =(Coin)coins.get(i); if (c.equals(aCoin)) return true; //found a match } return false; //no match in the entire array list }... }

Counting public class Purse { public int count(Coin aCoin) { int matches = 0; for (int i = 0; i < coins.size(); i++) { Coin c =(Coin)coins.get(i); if (c.equals(aCoin)) matches++;//found a match } return matches; }... }

Finding Maximum public class Purse { public Coin getMaximum() { Coin max =(Coin)coins.get(0); for (int i = 1; i max.getValue()) max =c; } return max; }... }

File Purse.java 1 import java.util.ArrayList; 2 3 /** 4 A purse holds a collection of coins. 5 */ 6 public class Purse 7 { 8 /** 9 Constructs an empty purse. 10 */ 11 public Purse() 12 { 13 coins = new ArrayList(); 14 } /** 17 Add a coin to the purse.

aCoin the coin to add 19 */ 20 public void add(Coin aCoin) 21 { 22 coins.add(aCoin); 23 } /** 26 Get the total value of the coins in the purse. the sum of all coin values 28 */ 29 public double getTotal() 30 { 31 double total = 0; 32 for (int i = 0; i < coins.size(); i++) 33 { 34 Coin aCoin = (Coin)coins.get(i); 35 total = total + aCoin.getValue(); 36 } 37 return total;

38 } /** 41 Counts the number of coins in the purse the number of coins 43 */ 44 public int count() 45 { 46 return coins.size(); 47 } /** 50 Tests if the purse has a coin that matches 51 a given coin. aCoin the coin to match true if there is a coin equal to aCoin 54 */ 55 public boolean find(Coin aCoin) 56 { 57 for (int i = 0; i < coins.size(); i++)

58 { 59 Coin c = (Coin)coins.get(i); 60 if (c.equals(aCoin)) return true; // found a match 61 } 62 return false; // no match in the entire array list 63 } /** 66 Counts the number of coins in the purse that match 67 a given coin. aCoin the coin to match the number of coins equal to aCoin 70 */ 71 public int count(Coin aCoin) 72 { 73 int matches = 0; 74 for (int i = 0; i < coins.size(); i++) 75 { 76 Coin c = (Coin)coins.get(i); 77 if (c.equals(aCoin)) matches++; // found a match

78 } 79 return matches; 80 } /** 83 Finds the coin with the largest value. 84 (Precondition: The purse is not empty) a coin with maximum value in this purse 86 */ 87 Coin getMaximum() 88 { 89 Coin max = (Coin)coins.get(0); 90 for (int i = 1; i < coins.size(); i++) 91 { 92 Coin c = (Coin)coins.get(i); 93 if (c.getValue() > max.getValue()) 94 max = c; 95 } 96 return max; 97 }

98 99 private ArrayList coins; 100 } 101

Storing Numbers in an Array List Array lists store objects Use wrapper classes to store numbers Double wrapper = new Double(29.95); double unwrapped = wrapper.doubleValue() ArrayList data = new ArrayList(); data.add(wrapper); unwrapped = ((Double).data.get(i)).doubleValue(); Also have Integer and Boolean wrappers

Arrays Construct array: new double[10] Store in variable of type double[] double[] data = new double[10];

Arrays Arrays have fixed length Arrays have element of specific type, not Object Use [] to access element: data[4] = 29.95; Get array length as data.length. (Not a method!)

Syntax 13.1: Array Construction new typename[length] Example: new double[10] Purpose: To construct an array with a given number of elements.

Syntax 13.2: Array Element Access arrayReference[index] Example: a[4] = 29.95; double x = a[4]; Purpose: To access an element in an array

Copying Arrays –Copying an array reference yields a second reference to the same array double[] data = new double[10]; // fill array... double[] prices = data; previousprevious | start | nextstartnext previousprevious | start | nextstartnext

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

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

Adding and Removing Array Elements Add an element: System.arraycopy(data, i, data, i + 1, data.length - i - 1); data[i] = x;

Remove an element: System.arraycopy(data, i + 1, data, i, data.length - i - 1);

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: final int DATA_LENGTH = 100; double[] data = new double[DATA_LENGTH]; int dataSize = 0; Update dataSize as array is filled: data[dataSize] = x; dataSize++;

Partially Filled Arrays

Remember to stop at dataSize when looking at array elements: for (int i = 0; i < dataSize; i++) sum = sum + data[i]; Be careful not to overfill the array if (dataSize >= data.length) System.out.println("Sorry--array full"); Or grow the array: double newData = new double[2 * data.length]; System.arraycopy(data, 0, newData, 0, data.length); data = newData;

Growing an Array

File DataSet.java 1 /** 2 This class computes the average of a set of data values. 3 */ 4 public class DataSet 5 { 6 /** 7 Constructs an empty data set. 8 */ 9 public DataSet() 10 { 11 final int DATA_LENGTH = 100; 12 data = new double[DATA_LENGTH]; 13 dataSize = 0; 14 } /** 17 Adds a data value to the data set

x a data value 19 */ 20 public void add(double x) 21 { 22 if (dataSize >= data.length) 23 { 24 // make a new array of twice the size 25 double[] newData = new double[2 * data.length]; 26 // copy over all elements from data to newData 27 System.arraycopy(data, 0, newData, 0, data.length); 28 // abandon the old array and store in data 29 // a reference to the new array 30 data = newData; 31 } 32 data[dataSize] = x; 33 dataSize++; 34 } /** 37 Gets the average of the added data.

the average or 0 if no data has been added 39 */ 40 public double getAverage() 41 { 42 if (dataSize == 0) return 0; 43 double sum = 0; 44 for (int i = 0; i < dataSize; i++) 45 sum = sum + data[i]; 46 return sum / dataSize; 47 } private double[] data; 50 private int dataSize; 51 }

File DataSetTest.java 1 import java.util.Random; 2 3 /** 4 This program tests the DataSet class by adding 10,000 numbers 5 to the data set and computing the average. 6 */ 7 public class DataSetTest 8 { 9 public static void main(String[] args) 10 { 11 Random generator = new Random(); 12 DataSet data = new DataSet(); 13 final int COUNT = 10000; 14 System.out.println("Adding " + COUNT + " random numbers."); 15 for (int i = 0; i < COUNT; i++) 16 { 17 double x = generator.nextDouble();

18 data.add(x); 19 } 20 double average = data.getAverage(); 21 System.out.println("average=" + average); 22 } 23 }

Two-Dimensional Arrays Matrix with rows and columns Example: Tic Tac Toe board char[][] board = new char[3][3]; board[i][j] = 'x';

File TicTacToe.java 1 /** 2 A 3 x 3 Tic-Tac-Toe board. 3 */ 4 public class TicTacToe 5 { 6 /** 7 Constructs an empty board. 8 */ 9 public TicTacToe() 10 { 11 board = new char[ROWS][COLUMNS]; // fill with spaces 14 for (int i = 0; i < ROWS; i++) 15 for (int j = 0; j < COLUMNS; j++) 16 board[i][j] = ' '; 17 }

18 19 /** 20 Sets a field in the board. The field must be unoccupied. i the row index j the column index player the player ('x' or 'o') 24 */ 25 public void set(int i, int j, char player) 26 { 27 if (board[i][j] != ' ') 28 throw new IllegalArgumentException("Position occupied"); 29 board[i][j] = player; 30 } /** 33 Creates a string representation of the board such as 34 |x o| 35 | x | 36 | o| the string representation

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

File TicTacToeTest.java 1 import javax.swing.JOptionPane; 2 3 /** 4 This program tests the TicTacToe class by prompting the 5 user to set positions on the board and printing out the 6 result. 7 */ 8 public class TicTacToeTest 9 { 10 public static void main(String[] args) 11 { 12 char player = 'x'; 13 TicTacToe game = new TicTacToe(); 14 while (true) 15 { 16 System.out.println(game); // calls game.toString() 17 String input = JOptionPane.showInputDialog(

18 "Row for " + player + " (Cancel to exit)"); 19 if (input == null) System.exit(0); 20 int row = Integer.parseInt(input); 21 input = JOptionPane.showInputDialog( 22 "Column for " + player); 23 int column = Integer.parseInt(input); 24 game.set(row, column, player); 25 if (player == 'x') player = 'o'; else player = 'x'; 26 } 27 } 28 }