Lecture 121 CS110 Lecture 12 Tuesday, March 9, 2004 Announcements –hw5 due Thursday –Spring break next week Agenda –questions –ArrayList –TreeMap.

Slides:



Advertisements
Similar presentations
Why not just use Arrays? Java ArrayLists.
Advertisements

Introduction to Java 2 Programming Lecture 5 The Collections API.
Lecture 9: More on objects, classes, strings discuss hw3 assign hw4 default values for variables scope of variables and shadowing null reference and NullPointerException.
Singleton vs utility class  at first glance, the singleton pattern does not seem to offer any advantages to using a utility class  i.e., a utility class.
Collections & Loops Chapter 5 Copyright © 2012 Pearson Education, Inc.
CIT 590 Intro to Programming Java lecture 4. Agenda Types Collections – Arrays, ArrayLists, HashMaps Variable scoping Access modifiers – public, private,
Slides prepared by Rose Williams, Binghamton University Chapter 14 Generics and the ArrayList Class.
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.
CSci 143 Sets & Maps Adapted from Marty Stepp, University of Washington
1 Java intro Part 3. 2 Arrays in Java Store fixed number of values of a given type Arrays are objects –have attributes –must be constructed Array declaration:
Loops Notes adapted from Dr. Flores. It repeats a set of statements while a condition is true. while (condition) { execute these statements; } “while”
© The McGraw-Hill Companies, 2006 Chapter 17 The Java Collections Framework.
Lecture 171 CS110 Lecture 17 Thursday, April 1, 2004 Announcements –hw7 due tonight –pass/fail, withdraw deadline April 8 Agenda –Questions –Juno –JFile.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 10 *Arrays with more than one dimension *Java Collections API.
Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4.
1 More on Arrays Arrays of objects Command line arguments The ArrayList class Javadoc Review Lecture 8 notes and L&L 7.1 – 7.2 Reading for this lecture:
Lecture 161 CS110 Lecture 16 Tuesday, March 30, 2004 Announcements –hw7 due Thursday –pass/fail, withdraw deadline April 8 Agenda –Questions –toString.
15-Jul-15 Generics. ArrayList s and arrays A ArrayList is like an array of Object s, but... Arrays use [ ] syntax; ArrayList s use object syntax An ArrayList.
Chapter 10 2D Arrays Collection Classes. Topics Arrays with more than one dimension Java Collections API ArrayList Map.
Georgia Institute of Technology Making Text for the Web part 4 Barb Ericson Georgia Institute of Technology March 2006.
CSE 143 Lecture 7 Sets and Maps reading: ; 13.2 slides created by Marty Stepp
CSE373 Optional Section Java Collections 11/12/2013 Luyi Lu.
Random, Collections & Loops Chapter 5 Copyright © 2012 Pearson Education, Inc.
CS2110: SW Development Methods Textbook readings: MSD, Chapter 8 (Sect. 8.1 and 8.2) But we won’t implement our own, so study the section on Java’s Map.
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.
Lecture 61 CS110 Lecture 6 Thursday, February 12, 2004 Announcements –hw2 due today Agenda –questions –testing –modeling text files –declarations (classes,
Announcements  I will discuss the labtest and the written test #2 common mistakes, solution, etc. in the next class  not today as I am still waiting.
(c) University of Washington14-1 CSC 143 Java Collections.
CSE 143 Lecture 11 Maps Grammars slides created by Alyssa Harding
Lecture 21 CS110 Lecture 2 January 29, 2004 Announcements –hw1 part 1 – due right now –hw1 part 2 – due Tuesday night Questions Agenda –turnin –Object.
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
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.
Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.
Building Java Programs Chapter 11 Lecture 11-1: Sets and Maps reading:
Lecture 131 CS110 Lecture 13 Thursday, March 11, 2004 Announcements –hw5 due tonight –Spring break next week –hw6 due two weeks from tonight Agenda –questions.
Chapter 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
Lecture 71 CS110 Lecture 7 February 17, 2004 Announcements –hw3 due Thursday Agenda –questions –hw3 tips –getters and setters – information hiding –delegation.
Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.
CSC 142 P 1 CSC 142 Collections [Reading: Chapter 10]
1 Generics Chapter 21 Liang, Introduction to Java Programming.
Lists and the Collection Interface Chapter 4. 2 The List Interface and ArrayList Class So far, all we have is an array for storing a collection of elements.
Lecture 101 CS110 Lecture 10 Thursday, February Announcements –hw4 due tonight –Exam next Tuesday (sample posted) Agenda –questions –what’s on.
Mixing Static and Non-static
This recitation 1 An interesting point about A3: Using previous methods to avoid work in programming and debugging. How much time did you spend writing.
Lecture 71 CS110 Lecture 8 February 19, 2004 Announcements –hw3 due tonight –hw4 available, due Thursday February 26 –exam Tuesday March 2 Agenda –questions.
Copyright 2010 by Pearson Education Building Java Programs Chapter 10, 11 Lecture 22: 143 Preview optional reading: 10.1,
Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.
COMP 121 Week 8: Generic Collections. Objectives To understand type variables and how they are used in generic programming To be able to implement and.
©SoftMoore ConsultingSlide 1 Generics “Generics constitute the most significant change in the Java programming language since the 1.0 release.” – Cay Horstmann.
Java Classes Chapter 1. 2 Chapter Contents Objects and Classes Using Methods in a Java Class References and Aliases Arguments and Parameters Defining.
More Java: Static and Final, Abstract Class and Interface, Exceptions, Collections Framework 1 CS300.
Maps Nick Mouriski.
Introducing Arrays. Too Many Variables?  Remember, a variable is a data structure that can hold a single value at any given time.  What if I want to.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Collections Dwight Deugo Nesa Matic
CSE 143 Lecture 11: Sets and Maps reading:
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 6 GEORGE KOUTSOGIANNAKIS Copyright: 2016 Illinois Institute of Technology/George Koutsogiannakis 1.
More on Arrays Review of Arrays of ints, doubles, chars
CSE 413, Autumn 2002 Programming Languages
3 Introduction to Classes and Objects.
Road Map CS Concepts Data Structures Java Language Java Collections
Object Oriented Programming in java
Grouped Data Arrays, and Array Lists.
CS2110: Software Development Methods
slides created by Ethan Apter
slides created by Marty Stepp
Creating and Modifying Text part 3
Review: libraries and packages
Presentation transcript:

Lecture 121 CS110 Lecture 12 Tuesday, March 9, 2004 Announcements –hw5 due Thursday –Spring break next week Agenda –questions –ArrayList –TreeMap

Lecture 122 ArrayList A Collection class in the Java API Like an array: stores elements at positions 0,1,… Can grow as needed! Unlike an array in other ways too –stores only objects (not primitive types) –can store different kinds of objects simultaneously –you must cast when retrieving –send explicit messages instead of using [ ] for access Read ArrayListDemo.java

Lecture 123 Casting Syntax: (Bar)foo tells the compiler to treat object foo as something of type Bar ArrayList get returns an anonymous Object for (int i = 0; i<myList.size(); i++ ){ SimpleObject foo = (SimpleObject)myList.get(i); System.out.println (i + "\t" + foo.name); } Perhaps the compiler ought to know, but it doesn’t

Lecture 124 ArrayList API can store: any Object, not primitive types declaration: ArrayList myList creation: myList = new ArrayList( ) put at end: myList.add( obj ) put at index: myList.add( index, obj ) –moves later entries down the list get: (Type)myList.get( index ) –cast to proper Type after get replace: myList.set( index, obj ) remove: myList.remove( index ) size: myList.size( ) looping: for( ; ; )

Lecture 125 Boxes and arrows for ArrayList ArrayList Object 0: String SimpleObject name: String SimpleObject name: String SimpleObject name: Object 1: Object 2: "zero " " one " " two " ArrayList myList:

Lecture 126 hw5 array practice (sorting) ArrayList practice: modify Bank.java so that it uses an ArrayList of BankAccounts instead of an array –BankAccounts have numbers 0, 1, 2, … –Banker can open as many accounts as she likes!

Lecture 127 Maps arrays and ArrayLists locate entries by index –index is an integer position, starting at 0 A Map locates entries by key –key is often a String (think dictionary, phone book) A map stores key-value pairs –key: “Java” value: “a modern OO language” –key: “UMass” value: areaCode: 617 exchange: 287 PhoneNumber number: 5000

Lecture 128 Duplicates? The same value may appear more than once in a collection (array, ArrayList or Map) –my wife and I have the same phone number –“field” and “instance variable” have the same definition –in an array, foo[3] may == foo[7] In a Map, keys are unique If you want to arrange for one person to have more than one phone number or one word to have more than one definition you need to work harder (see last slides, JOI Chapter4)

Lecture 129 TreeMap Java API provides class TreeMap Don’t ask why it’s called that Key can be any Object (but our keys will always be String objects) TreeMaps, like ArrayLists –can grow –store Objects (references, not primitive types) –are heterogeneous can hold objects of different types need to cast what you get from a TreeMap

Lecture 1210 Directory Model windows folder Contains TextFiles (not other Folders - wait for Chapter 5) API: create, add file to, get file from, get size, get owner, get create/mod date Design: Directory object has a TreeMap field storing TextFile objects keyed by String filename You write this for homework

Lecture 1211 Dictionary Model a real dictionary A collection of definitions of words –A word is a String –A definition will be an instance of class Definition Design: Dictionary object has a TreeMap field storing Definition objects keyed by String words API: create, add entry, look up entry, get size, arrange for printing the whole Dictionary

Lecture 1212 Dictionary.java Architecture: a Dictionary object is a thin wrapper around a TreeMap Prepare to use classes in java.util package (line 6) private TreeMap instance variable –declared on line 18 –created in constructor (line 26) Put a Definition in this Dictionary: addEntry method (36) –parameters: String word, reference to Definition instance –delegate to TreeMap put method

Lecture 1213 Dictionary (continued) Look up a Definition: getEntry (line 48) –delegate to TreeMap get method, passing String word as the argument (line 50) –cast retrieved anonymous object to Definition –return the Definition ( null if not found) How large is this Dictionary? getSize (line 61) –delegate to TreeMap size method What’s a Definition? –just one String field, set in constructor, access by public getter (toString) –would be richer in a real dictionary (pronunciation, etymology, …)

Lecture 1214 TreeMap boxes and arrows entries: "shape" TreeMap Dictionary TreeMap "quadrilateral" "a shape with four sides" entries: "a geometric object in a plane" entries: Definition String definition: entries: Definition String definition: Object

Lecture 1215 Class Lookup Dictionary has no unit test Class Lookup is a client for Dictionary (and tests it thoroughly) All of Lookup is static > java Lookup … all Lookup.java sends toString messages to a Definition object (line 53) and to a Dictionary object (line 103)

Lecture 1216 Looping on a TreeMap To print the whole Dictionary, Lookup sends a toString message, invoking Dictionary toString method (line 70) Subtle, since there’s no index to loop with Uses an Iterator object - Java tool custom designed for looping Iterator API has just two methods: –boolean hasNext() –Object next()

Lecture 1217 Set allWords = entries.keySet(); Iterator wordIterator = allWords.iterator(); ask the entries field (a TreeMap) for its keySet ask the keySet to give you an Iterator wI is like a list of the keys in the entries Map You can infer from this code that –Set and Iterator are classes in the Java API –keySet is a method in class TreeMap; it returns a Set –iterator is a method in class Set; it returns an Iterator Getting an Iterator

Lecture 1218 while ( wordIterator.hasNext() ) { word = (String)wordIterator.next(); definition = this.getEntry( word ); str += word + ":\n" + definition.toString() + "\n"; } hasNext() returns false when at end of list next() returns a reference to the next Object in the list cast that to a String since that’s what the key is Using an Iterator

Lecture 1219 while ( wordIterator.hasNext() ) { word = (String)wordIterator.next(); definition = this.getEntry( word ); str += word + ":\n" + definition.toString() + "\n"; } use the key to look up a Definition send the Definition a toString message add two lines to the String str we are building to represent the whole Dictionary Building a multiline String

Lecture 1220 TreeMap summary declaration: TreeMap mapName; creation: new TreeMap( ); put: mapName.put(Object key, Object obj) get: (Type)mapName.get(Object key) cast to proper Type length: mapName.size( ) looping: use Iterator mapName.keySet( ).iterator( )

Lecture 1221 Collections of collections Dictionary might map a word to an ArrayList of definitions Screen maintains a private field that’s an array of arrays of char: private char[][] pixels;

Lecture 1222 Figure 4.5 Object structure of a 2x3 Screen 0: char[][] 1: char[] ‘ 5 1: 2: 0: ‘ int width: int height: char[][] pixels: 2 3 char[] ‘ 5 1: 2: 0: ‘ Screen

Lecture 1223 hw6 Due Thursday after Spring break TreeMap practice –class Directory –little Bank, using a TreeMap