Lecture Notes – Arrays and ArrayLists (Ch 7-8)

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 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.
Designing Classes Chapter 8. Classes Collection of objects Objects are not actions Class names – Nouns Method names – Verbs What Makes a Good Class Represent.
Our BankAccount class should define three methods  deposit  withdraw  getBalance How a programmer will carry out these operations?  We assume that.
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[]
Unit 261 Introduction to Searching and Sorting Comparable Interface Comparator Interface Algorithm Complexity Classes Exercises.
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.
Review Java.
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:
Class Library, Formatting, Wrapper Classes, and JUnit Testing
Week 10 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
7. Arrays. Topics Declaring and Using Arrays Some Array Algorithms Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList.
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
Static. Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. A static method does not operate on an object double dY.
Arrays Pepper. What is an Array A box that holds many of the exact same type in mini-boxes A number points to the mini-box The number starts at 0 String.
Arrays Construct array: new double[10] Store in variable of type double[] double[] data = new double[10];
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.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. A class represents a single concept from the problem domain, or a.
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.
int [] scores = new int [10];
© 2004 Pearson Addison-Wesley. All rights reserved September 5, 2007 Packages & Random and Math Classes ComS 207: Programming I (in Java) Iowa State University,
Chapter 7 – Arrays and Array Lists Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Building Java Programs Chapter 7 Arrays Copyright (c) Pearson All rights reserved.
Arrays Chapter 7.
CMSC 202 ArrayList Aug 9, 2007.
Chapter 7 – Arrays and Array Lists
Sixth Lecture ArrayList Abstract Class and Interface
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.
Chapter 7 User-Defined Methods.
Principles of Computer Science I
Chapter 7 – Arrays and Array Lists
Chapter 8 – Arrays and Array Lists
7.6 Common Array Algorithm: Filling
Classes, Libraries & Packages
Introduction to Computer Science and Object-Oriented Programming
Building Java Programs
Exercise on Java Basics
ARRAYS & ARRAY LISTS.
Slides by Donald W. Smith
Building Java Programs
CMSC 202 ArrayList Aug 9, 2007.
int [] scores = new int [10];
Building Java Programs
Building Java Programs
CMSC 202 ArrayList Aug 9, 2007.
python.reset() Also moving to a more reasonable room (CSE 403)
int [] scores = new int [10];
Arrays and Array Lists CS 21a.
CS 200 Objects and ArrayList
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Ps Module 7 – Part II 2D Arrays and LISTS 5/26/2019 CSE 1321 Module 7.
CS 200 Objects and ArrayList
First Semester Review.
Presentation transcript:

Lecture Notes – Arrays and ArrayLists (Ch 7-8) Yonglei Tao

Arrays Hold sequences of values of primitive types or objects When an array is created, its values are initialized zero, false, or null int [] scores; scores = new int [10]; for (int i = 0; i < scores.length; i++) scores[i] = i * i; for (int n: scores) // a “for each” loop System.out.println (n);

Arrays (Cont.) A two-dimensional array String[] names = {“Ed”, “Bob”, “Cindy”}; System.out.println( names[0] ); if ( names[0].equals(“Ed”)) … String[] list = new String[5]; list[0] = new String(“Tom”); … A two-dimensional array int rows = 10, cols = 20; int [][] table = new int[rows][cols];

Split String into Array String s = “John Doe; 25; Spring Lake”; String[] tokens = s.split(“;”); if (tokens.length == 3) { String name = tokens[0]; int age = Integer.parseInt(tokens[1]); String city = tokens[2]; … } Other ways to do?

Linear Search /** Finds a value in an array, using the linear search algorithm. @param v the value to search @param a the array to be searched @return the index at which the value occurs, or -1 if it does not occur in the array */ public int search(int v, int[] a) { for (int i = 0; i < a.length; i++) { if (a[i] == v) return i; } return -1;

Discussion Given the number of days from the new year’s day, how to find out in which month it falls? int findMonth (int numOfDays) { int [] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; }

Partially Filled Arrays - Loading double [] values = new double [20]; int numValues = 0; Scanner scan = new Scanner(System.in); while (scan.hasNextDouble() && numValues < values.length) { values[numValues] = scan.nextDouble(); numValues ++; } for (int i = 0; i < numValues; i++) { System.out.println(values[i]);

Ordered Arrays - Insert while (scan.hasNextDouble() && numValues < values.length) { int newValue = scan.nextDouble(); int pos = 0; while ( values[pos] > newValue ) pos++; for (int i = numValues ; i > pos; i--) values[i] = values[i - 1]; values[pos] = newValue; numValues ++; } Consider a general case first and then make sure it works for special cases as well.

Common Array Algorithm – Array Copy double[] values = new double[6]; . . . // Fill array values double[] prices = values; ? double[] prices = Arrays.copyOf(values, values.length); values = Arrays.copyOf(values, 2 * values.length);

Class ArrayList A sequence of objects Can grow and shrink as needed A generic class with a type parameter ArrayList<String> classlist = new ArrayList<String> (); classlist.add ( “Ed” ); classlist.add ( “Bob” ); classlist.add ( “Cindy” );

ArrayList (Cont.) for (int i = 0; i < classlist.size(); i++ ) { String name = classlist.get(i); System.out.println (name); // Ed, Bob, Cindy } for ( String name: classlist ) System.out.println (name); classlist.set (1, “Tim”); // Ed, Tim, Cindy classlist.add (1, “Ron”); // Ed, Ron, Tim, Cindy classlist.remove (2); // Ed, Ron, Cindy

ArrayList Algorithm - Search int pos = 0; boolean found = false; while ( pos < classlist.size() && !found ) { if ( classlist.get(pos) > 100 ) found = true; else pos++; } if ( found ) { System.out.println("Position: " + pos); } { System.out.println("Not found"); }

Arrays vs. ArrayLists When do you use which? Element type Number of elements Basic operations Locate insert (at the front, in the middle, at the end) delete (the first, a middle one, the last)

Classes Each represents an entity in the application domain Keeps its information Provides operations to process the information Objects are instances of a class Members instance variables private (instance) methods private (instance) methods public

Method Parameter // a method call // method definition obj.doIt ( num, name ); // method definition public void doIt ( int n, String s ) { n += 4; s = “Mr. “ + s; } Every thing is passed by value “Tom” 6 6

Method Parameter (Cont.) obj.update ( num, book ); System.out.println(“Price is “ + book.getPrice()); … public void update ( int n, Book b ) { n = n + 10; b.setPrice(110.50); } “Big Java” 125.50

Overloaded Methods // Methods of class MyClass public void doIt (int n) { … } public void doIt (char c) { … } public void doIt (int n, String s) { … } // Method calls MyClass obj = new MyClass(); obj.doIt(5); obj.doIt(‘a’); obj.doIt(10, “xyz”);

Static Members of a Class Instance variable One copy per object Static variable One copy per class Static Method Operating on class-wide data Examples Integer.MAX_VALUE, Integer.MIN_VALUE Math.pow(x, y), Math.sqrt(x)

Wrapper Classes

Auto Boxing and Unboxing int n = 25; Integer num = n; // same as num = new Integer (n); Double rate = 5.25; double d = rate; rate = rate + i; Boolean isDone = new Boolean(false); ArrayList<Double> values = new ArrayList<Double>(); values.add(29.95); double x = values.get(0); // inefficient

Packages in Java Package Purpose Sample Class Language support java.lang Language support Math java.util Utilities Random java.io Input and output PrintStream java.awt Abstract Windowing Toolkit Color java.applet Applets Applet java.net Networking Socket java.sql Database Access ResultSet javax.swing Swing user interface JButton omg.w3c.dom Document Object Model for XML documents Document

Packages - Organizing related classes To put classes in a package package cis500.proj1; public class MyClass { ... } To use class with importing import cis500.proj1.MyClass; Or import cis500.proj1.*;

Bank class stores an array list of bank accounts Class Bank Bank class stores an array list of bank accounts 1 import java.util.ArrayList; 2 3 /** 4 This bank contains a collection of bank accounts. 5 */ 6 public class Bank 7 { 8 private ArrayList<BankAccount> accounts; 9 10 /** 11 Constructs a bank with no bank accounts. 12 */ 13 public Bank() 14 { 15 accounts = new ArrayList<BankAccount>(); 16 } 17

Class Bank (cont.) 18 /** 19 Adds an account to this bank. 18 /** 19 Adds an account to this bank. 20 @param a the account to add 21 */ 22 public void addAccount(BankAccount a) 23 { 24 accounts.add(a); 25 } 26 27 /** 28 Gets the sum of the balances of all accounts in this bank. 29 @return the sum of the balances 30 */ 31 public double getTotalBalance() 32 { 33 double total = 0; 34 for (BankAccount a : accounts) 35 { 36 total = total + a.getBalance(); 37 } 38 return total; 39 } 40

Class Bank (cont.) 41 /** 42 Counts the number of bank accounts whose balance is at 43 least a given value. 44 @param atLeast the balance required to count an account 45 @return the number of accounts having least the given balance 46 */ 47 public int countBalancesAtLeast(double atLeast) 48 { 49 int matches = 0; 50 for (BankAccount a : accounts) 51 { 52 if (a.getBalance() >= atLeast) matches++; // Found a match 53 } 54 return matches; 55 } 56

Class Bank (cont.) 57 /** 58 Finds a bank account with a given number. 57 /** 58 Finds a bank account with a given number. 59 @param accountNumber the number to find 60 @return the account with the given number, or null if there 61 is no such account 62 */ 63 public BankAccount find(int accountNumber) 64 { 65 for (BankAccount a : accounts) 66 { 67 if (a.getAccountNumber() == accountNumber) // Found a match 68 return a; 69 } 70 return null; // No match in the entire array list 71 } 72

Class Bank (cont.) 73 /** 74 Gets the bank account with the largest balance. 75 @return the account with the largest balance, or null if the 76 bank has no accounts 77 */ 78 public BankAccount getMaximum() 79 { 80 if (accounts.size() == 0) return null; 81 BankAccount largestYet = accounts.get(0); 82 for (int i = 1; i < accounts.size(); i++) 83 { 84 BankAccount a = accounts.get(i); 85 if (a.getBalance() > largestYet.getBalance()) 86 largestYet = a; 87 } 88 return largestYet; 89 } 90 }

Class BankTester 1 /** 2 This program tests the Bank class. 3 */ 1 /** 2 This program tests the Bank class. 3 */ 4 public class BankTester 5 { 6 public static void main(String[] args) 7 { 8 Bank firstBankOfJava = new Bank(); 9 firstBankOfJava.addAccount(new BankAccount(1001, 20000)); 10 firstBankOfJava.addAccount(new BankAccount(1015, 10000)); 11 firstBankOfJava.addAccount(new BankAccount(1729, 15000)); 12 13 double threshold = 15000; 14 int count = firstBankOfJava.countBalancesAtLeast(threshold); 15 System.out.println("Count: " + count); 16 System.out.println("Expected: 2"); 17

Class BankTester (cont.) 18 int accountNumber = 1015; 19 BankAccount account = firstBankOfJava.find(accountNumber); 20 if (account == null) 21 System.out.println("No matching account"); 22 else 23 System.out.println("Balance of matching account: " 24 + account.getBalance()); 25 System.out.println("Expected: 10000"); 26 27 BankAccount max = firstBankOfJava.getMaximum(); 28 System.out.println("Account with largest balance: " 29 + max.getAccountNumber()); 30 System.out.println("Expected: 1001"); 31 } 32 } Program Run: Count: 2 Expected: 2 Balance of matching account: 10000.0 Expected: 10000 Account with largest balance: 1001 Expected: 1001