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.

Slides:



Advertisements
Similar presentations
Class Relationships Part 1: Composition and Association CS 21a: Introduction to Computing I First Semester,
Advertisements

Arrays and ArrayLists Ananda Gunawardena. Introduction Array is a useful and powerful aggregate data structure presence in modern programming languages.
Arrays. What is an array An array is used to store a collection of data It is a collection of variables of the same type.
Introduction to Object-Oriented Programming CS 21a: Introduction to Computing I First Semester,
CIT 590 Intro to Programming Java lecture 4. Agenda Types Collections – Arrays, ArrayLists, HashMaps Variable scoping Access modifiers – public, private,
Chapter 7 – Arrays.
Arrays Horstmann, Chapter 8. arrays Fintan Array of chars For example, a String variable contains an array of characters: An array is a data structure.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
1 More on Arrays Passing arrays to or from methods Arrays of objects Command line arguments Variable length parameter lists Two dimensional arrays Reading.
©2004 Brooks/Cole Chapter 8 Arrays. Figures ©2004 Brooks/Cole CS 119: Intro to JavaFall 2005 Sometimes we have lists of data values that all need to be.
1 Lecture Today’s topic Arrays Reading for this Lecture: –Chaper 11.
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.
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
Arrays. A problem with simple variables One variable holds one value –The value may change over time, but at any given time, a variable holds a single.
Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4.
Class design. int month; int year class Month Defining Classes A class contains data declarations (state) and method declarations (behaviors) Data declarations.
Previous Exam 1.0. Question 1 - a Is the following statement true or false? Briefly explain your answer. A && B is the same as B && A for any Boolean.
© The McGraw-Hill Companies, 2006 Chapter 7 Implementing classes.
Arrays. A problem with simple variables One variable holds one value –The value may change over time, but at any given time, a variable holds a single.
More Arrays Length, constants, and arrays of arrays By Greg Butler.
Java Programming Review (Part I) Enterprise Systems Programming.
Java Unit 9: Arrays Declaring and Processing Arrays.
Data Objects (revisited) Recall that values are stored in data objects, and that each data object holds one value of a particular type. Data objects may.
CSC Programming I Lecture 8 September 9, 2002.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester,
Classes CS 21a: Introduction to Computing I First Semester,
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
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.
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
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.
Chapter 8: Arrays.
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 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
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Working with arrays (we will use an array of double as example)
CSE 501N Fall ‘09 08: Arrays 22 September 2009 Nicholas Leidenfrost.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
CSC1401 Classes - 2. Learning Goals Computing concepts Adding a method To show the pictures in the slide show Creating accessors and modifiers That protect.
Lecture 101 CS110 Lecture 10 Thursday, February Announcements –hw4 due tonight –Exam next Tuesday (sample posted) Agenda –questions –what’s on.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
Odds and Ends. CS 21a 09/18/05 L14: Odds & Ends Slide 2 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights.
Using Objects. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L7: Objects Slide 2 Java.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
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.
©SoftMoore ConsultingSlide 1 Generics “Generics constitute the most significant change in the Java programming language since the 1.0 release.” – Cay Horstmann.
Arrays and Lists: Handling Infinite Data CS 21a: Introduction to Computing I First Semester,
Inheritance and Subclasses CS 21a. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L16:
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
Arrays What is an array… –A data structure that holds a set of homogenous elements (of the same type) –Associate a set of numbers with a single variable.
Outline Anatomy of a Class Encapsulation Anatomy of a Method Graphical Objects Graphical User Interfaces Buttons and Text Fields Copyright © 2012 Pearson.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Arrays Chap. 9 Storing Collections of Values 1. Introductory Example Problem: Teachers need to be able to compute a variety of grading statistics for.
Arrays. What is an array? An array is a collection of data types. For example, what if I wanted to 10 different integers? int num1; int num2; int num3;
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Chapter VII: Arrays.
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.
Anatomy of a Method.
Arrays and Array Lists CS 21a.
Corresponds with Chapter 5
Arrays.
Presentation transcript:

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 Java application declare three variables of type double read in String values for each of them and convert print them out starting with the last variable read in public static void main( String[] args ) throws IOException { String temp; double num1, num2, num3; temp = console.readLine(); num1 = Double.parseDouble(temp); temp = cosole.readLine(); num2 = Double.parseDouble(temp); temp = console.readLine(); num3 = Double.parseDouble(temp); System.out.println( num3 ); System.out.println( num2 ); System.out.println( num1 ); }

Generalizing a Program Suppose we wanted the same program but wanted 10 instead of 3 numbers? Suppose we wanted to read in 1000 numbers? More than 3000 lines of code if we used the same approach! Solution: arrays

Arrays pronounced “ ar-ray ”, w/ stress on 2 nd syllable Definition collection of elements of the same type each element is accessed through an index In Java, declaration:double[] nums; creation:nums = new double[8]; use:nums[3] = 6.6; Note: starting index is 0 (0 to 7, above) double nums[] is also legal, but double[] nums is preferred, since it emphasizes that the type is double[] (“double array” or “array of doubles”)

Visualizing an Array Declare: double[] nums; nums null

Visualizing an Array nums Declare: double[] nums; Create: nums = new double[8];

Visualizing an Array Declare: double[] nums; Create: nums = new double[8]; Use: nums[3] = 6.6; nums

Reversing 10 numbers Use arrays and loops declare double[] nums create new double[10] use a for-statement to read in the numbers use a for-statement to print them out in reverse public static void main( String[] args ) throws IOException { double[] nums = new double[10]; for ( int i = 0; i < 10; i++ ) { String temp = console.readLine(); nums[i] = Double.parseDouble(temp); } for ( int i = 9; i >= 0; i-- ) { System.out.println( nums[i] ); }

Scaling up What if you want to change the number of elements? would have to find and change all places using 10 (including the 9 in the for loop) very tedious and error-prone public static void main( String[] args ) throws IOException { double[] nums = new double[10]; for ( int i = 0; i < 10; i++ ) { String temp = console.readLine(); nums[i] = Double.parseDouble(temp); } for ( int i = 9; i >= 0; i-- ) { System.out.println( nums[i] ); }

Using Constants What if you want to change the number of elements? would have to find and change all places using 10 (including the 9 in the for loop) very tedious and error-prone Solution: use a constant public class ReverseArray { … public static final int MAX = 10; public static void main( String[] args ) throws IOException { double[] nums = new double[MAX]; for ( int i = 0; i < MAX; i++ ) { String temp = console.readLine(); nums[i] = Double.parseDouble(temp); } for ( int i = MAX - 1; i >= 0; i-- ) { System.out.println( nums[i] ); }

A constant has to be a class-wide variable (not a local variable) Important keywords static -- means value is shared by all instances (more later) final -- means value can ’ t be changed (i.e., it ’ s a constant) Capitalization ALL_CAPS, words separated by underscore Using Constants public class ReverseArray { … public static final int MAX = 10; public static void main( String[] args ) throws IOException { double[] nums = new double[MAX]; for ( int i = 0; i < MAX; i++ ) { String temp = console.readLine(); nums[i] = Double.parseDouble(temp); } for ( int i = MAX - 1; i >= 0; i-- ) { System.out.println( nums[i] ); }

Constants and “ Magic Numbers ” Constants are useful for “ magic numbers ” – i.e., specific values that are used throughout the code e.g., MAX_LENGTH, SCREEN_WIDTH, PI, BLUE, DASHED_LINE, etc. Useful because makes code more readable and maintainable e.g., WHITE is easier to understand and easier to remember than 255 makes modifications easier e.g., in reversing program example, we just need to change MAX. No need to look for 10 and 9 and change them.

Problem 2: Collection of Objects How can we write Bank so it can handle a larger number of BankAccounts? Right now, we can only handle a small number of accounts (2 or 3) getBalance( “Bob”, “4321” ) withdraw( “Alice”, “1234”, 200 )

Solution: Array of Objects Declaration BankAccount[] accounts; Creation of the Array accounts = new BankAccount[5]; creates an array of references to BankAccounts but no actual BankAccounts yet Creation of Objects for ( i = 0; i < 5; i++ ) { accounts[i] = new BankAccount(); } creates the BankAccounts themselves and assigns these to the references

Visualizing an Array of Objects Declare: BankAccount[] accounts; accounts null

Create array: accounts = new BankAccount[5]; Visualizing an Array of Objects Declare: BankAccount[] accounts; null BankAccount-type references accounts

null Create array: accounts = new BankAccount[5]; Visualizing an Array of Objects Declare: BankAccount[] accounts; Create objects: for ( i = 0; i < 5; i++ ) { accounts[i] = new BankAccount(i * 10); } null BankAccount-type references BankAccount balance 40 BankAccount balance 30 BankAccount balance 20 BankAccount balance 10 BankAccount balance 0 acounts

Visualizing an Array of Objects Use objects: e.g., accounts[3].getBalance(); (returns 30) Create array: accounts = new BankAccount[5]; Declare: BankAccount[] accounts; acounts Create objects: for ( i = 0; i < 5; i++ ) { accounts[i] = new BankAccount(i * 10); } null BankAccount-type references BankAccount balance 40 BankAccount balance 30 BankAccount balance 20 BankAccount balance 10 BankAccount balance 0

Approach Include a name field in BankAccount Create set and get methods for this field Declare an array of BankAccount objects Use a loop in the findAccount() method of Bank

A field representing the acct name has been added: acctName Constructor has been modified to accept an initial balance Set and get methods were created to access acctName Approach public class BankAccount { private double balance; private String acctName; public BankAccount( double initBalance ) { balance = initBalance; } public void setAcctName( String name ) { acctName = name; } public String getAcctName() { return acctName; } … }

A field representing an array of BankAccounts was added: accounts There is also a constant representing the maximum amount of bankAccounts bank can handle: MAX The array is initialized in the constructor. It is also populated with 2 BankAccount objects named “ john ” and “ marsha ” Approach public class Bank { private BankAccount[] accounts; private static final int MAX = 10; public Bank() { accounts = new BankAccount[MAX]; accounts[0] = new BankAccount(100); accounts[0].setAcctName(“john”); accounts[1] = new BankAccount(200); accounts[1].setAcctName(“marsha”); } … }

findAccount contains a for- statement that searches for the appropriate account The getName() method of an account is used to get the name and compare it with the name parameter Approach public class Bank { … private BankAccount findAccount( String name ) { for( int x = 0; x < MAX; x++ ) { if( accounts[x].getAcctName().equals(name) ) { return accounts[x]; } return null; } … } Be careful when writing code like this. Doing this gives a NullPointerException if no BankAccount instance is assigned to that location.

A reference to the correct account is returned when it is found, otherwise the value returned is null A return statement is put inside the for-statement to “ break out ” of the loop when the correct account has been found Approach public class Bank { … private BankAccount findAccount( String name ) { for(int x = 0; x < MAX; x++) { if ( accounts[x] != null ) { if( accounts[x].getAcctName().equals(name) ) { return accounts[x]; } return null; } … } One possible alternative as this first checks if the location contains an instance of BankAccount (i.e., not null)

Approach public class Bank { … private BankAccount findAccount( String name ) { for(int x = 0; x < numAccounts; x++) { if( accounts[x].getAcctName().equals(name) ) { return accounts[x]; } return null; } … } Another possible alternative is to change the limit of x to the actual number of accounts the array contains.

Approach What is the value of numAccounts? public class Bank { private BankAccount[] accounts; private static final int MAX = 10; private int numAccounts = 0; public Bank() { accounts = new BankAccount[MAX]; accounts[0] = new BankAccount(100); accounts[0].setAcctName(“john”); accounts[1] = new BankAccount(200); accounts[1].setAcctName(“marsha”); numAccounts = 2; } … }

Creating new BankAccounts public void openAccount( String name, int initbal ) { if ( numAccounts < MAX ) { accounts[numAccounts] = new BankAccount( initbal ); accounts[numAccounts].setAcctName( name ); numAccounts++; } else { System.out.println( "Maximum number of accounts reached" ); }

Using openAccount as a convenience method In the Bank ’ s constructor: public Bank() { accounts = new BankAccount[MAX]; openAccount( "john", 1000 ); openAccount( "marsha", 2000 ); }

More About Arrays Arrays are objects the array variable is just a reference to the actual array that contains the values need to use “ new ” after declaring passed as a reference when used as method parameter Special features a public final int length field returns the array size in recent example, accounts.length would return 10 [] operator only work with arrays

More About Arrays ArrayIndexOutOfBounds exception valid indices for array of size n: 0 to n-1 any access to other indices causes an error Array size can ’ t be changed after array is created To expand array, we need to create a new array, copy old array contents, then point array variable to new array

Array Initializers You can initialize an array with the following syntax: String[] responses = { “ Hello ”, “ Hi ”, “ How are you ”, “ How do you do ” }; Can be used for fields, local variables, and even constants

Useful Pattern Put different responses for different cases in an array String[] responses = { “ Hello ”, “ Hi ”, “ How are you ”, “ How do you do ” }; Assign an integer to represent different cases In this case 0 means the program will say “ Hello ”, 1 means it will say “ Hi ”, etc. Now you can generate the data for each case accordingly e.g., What does the following code do? int greetingCase = Math.random() * responses.length; String greeting = responses[greetingCase] + “ World ” ; System.out.println( greeting );

Multi-dimensional Arrays (Optional) A natural extension of simple (1D) arrays 2D declaration: char[][] grid; think “ array of arrays ” Array creation grid = new char[10][20]; // 10 rows, 20 columns Another way grid = new char[10][]; // creates array of 10 char[] ’ s for (i = 0; i < 10; i++) { grid[i] = new char[20]; // creates a size-20 array } This way allows for varying row sizes

Create array of rows: grid = new char[5][]; Visualizing 2D Arrays Declare: char[][] grid; Create rows: for ( i = 0; i < 5; i++ ) { grid[i] = new char[3]; } char[][] null char[]-type references Use objects: e.g., grid[3][2] = ‘C’ C

Using 2D Arrays To refer to individual element, use two indices e.g., grid[2][1] = ‘ X ’ ; Using only one index refers to a single dimensional array e.g., grid[4] refers to row 4 grid[4].length is the length of row 4 (in this case, it ’ s 3) The array variable by itself refers to the top-level array (i.e., the array of rows) grid.length is the length of the array of rows (i.e., it ’ s the number of rows)

Problem 3, Flexible collections How can we write Bank so it can have an arbitrary number of BankAccounts? Right now, we can only handle a small and fixed number of accounts (2 or 3) getBalance( “Bob”, “4321” ) withdraw( “Alice”, “1234”, 200 )

The Java Collections Framework A set of classes that you can use for containing arbitrarily large collections of objects To use, you must say import java.util.*; at the top of your code Some basic Collections classes ArrayList, Vector HashMap, Hashtable

Indexed list of objects that automatically resizes The list is ordered, with each object in the list having an index, from 0 to n-1 Most commonly used methods boolean add( E element ) int size() E get( int index ) E set( int index, E element ) plus others (see API docs) ArrayList “Bart” “Lisa” “Maggie” ArrayList names Note: ArrayLists in Java 5 is used slightly differently from its previous versions.

ArrayList ArrayList Example import java.util.*; public class ArrayListDemo1 { public void execute() { ArrayList names = new ArrayList (); names.add( "Bart" ); names.add( "Lisa" ); names.add( "Maggie" ); for ( int i = 0; i < names.size(); i++ ) { System.out.println( names.get( i ) ); } names.set( 1, "Homer" ); names.add( "Marge" ); for ( int i = 0; i < names.size(); i++ ) { System.out.println( names.get( i ) ); } 0 “Bart” 1 “Lisa” 2 “Maggie” ArrayList names 3 “Marge” “Homer” You have to specify the type of object it has to store.

import java.util.*; public class ArrayListDemoWithBankAccounts { public void execute() { ArrayList accts = new ArrayList (); accts.add( new BankAccount( 2000 ) ); accts.get(0).setAcctName( “ Alice ” ); accts.add( new BankAccount( 1000 ) ); accts.get(1).setAcctName( “ Bob ” )); for ( int i = 0; i < accts.size(); i++ ) { BankAccount curAccount = accts.get( i ); System.out.println( "Bank Account #" + i + "Owner: " + curAccount.getAcctName() + ", " + "Balance: " + curAccount.getBalance() ); } ArrayList Using Other Types 0 1 ArrayList accts “Alice” BankAccount int balance 2000 String name BankAccount int balance 1000 String name “Bob”

Using an index … for ( int i = 0; i < accts.size(); i++ ) { BankAccount curAccount = accts.get( i ); System.out.println( … ); } Using an “ enhanced for ” … for ( BankAccount b : accts ) { System.out.println( b.getBalance() ); } Looping through ArrayLists Simpler than a regular for loop. All you have to specify is the object (BankAccount) and the ArrayList (accts).

Exercises Modify the Bank class, add a createAccount() method that adds another BankAccount object for the Bank to manage. First, do this using an array (accounts). Then, convert Bank from arrays to ArrayLists.