Title: Looping on a TreeMap
1Looping on a TreeMap
- To print the whole Dictionary, Lookup sends a
toString message, invoking Dictionary
toString method (line 70) - Subtle, since theres 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()
2Getting an Iterator
- 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
- wordIterator is like a list of the keys in the
entries Map - You can infer (figure out) 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
3Using an Iterator
- while ( wordIterator.hasNext() )
- word (String)wordIterator.next()
- definition this.getEntry( word )
- str word "\n"
definition.toString() "\n" -
- wordIterator.hasNext() returns false when at end
of list - wordIterator.next() returns a reference to the
next Object in the list - cast that to a String since thats what the key is
4Using an Iterator
- 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
5TreeMap summary
- declaration TreeMap myMap
- creation myMap new TreeMap( )
- put myMap.put(Object key, Object
obj) - get (Type)myMap.get(Object key)
- cast to proper
Type - length myMap.size( )
- looping use Iterator
myMap.keySet( ).iterator( )
6Collections of collections
- Dictionary might map a word to an ArrayList of
definitions - Screen maintains a private field thats an array
of arrays of char - private char pixels
7Design problem
- Bigbank and Littlebank are similar but different
- Both have fields
- name, balance, transaction count (same meaning)
- accountList (different meanings)
- Both have methods
- visit, processTransaction, getBalance, (same
code) - whichAccount, report (different code)
- Can we write big and little Bank classes
without copying code?
8Design problem
- HLine and VLine each have length, paintChar, with
setters and getters - Box and Frame each have width, height, paintChar,
with setters and getters - Every shape has a paintOn method, but each kind
of shape paints itself differently - Can we write these classes without copying code?
9Design problem
- Directory should store TextFiles and Directories
- Directory and TextFile both have
- owner, create/mod date (same meaning)
- size, contents (different meanings)
- Directory has methods to add to, get from and
loop on its contents (the TreeMap of files in it) - TextFile has methods to manipulate its text
- Can we write these classes without copying code?
10Inheritance
- Copy code and change a little bit
? design problem - cant see similarities and differences
- bugs must be fixed in two places
- Inheritance solves this problem
- Inheritance is the next Big Thing in OOP (sending
messages is the first Big Thing)
11class JFile
- Describes what Directories and TextFiles share
- An abstract class ( never new JFile() )
- Four fields (instance variables) - lines 23-26
- Some getters and setters - 84, 95, 106, 115, 126
- Client can send those messages to a Directory or
a TextFile (no need to write the methods in both
classes)
12class JFile
- getSize()
- API same for Directory and TextFile
- Behavior different!
- line 67 declares an abstract method
- public abstract int getSize() // not
- Each child class (subclass) must provide code
- TextFile.java - line 54 - delegates to String
- Directory.java - line 43 - delegates to TreeMap
13Inheritance
class JFile - fields and methods needed by all
child classes (deal with owner and Dates)
class Directory - fields and methods just for
Directory (TreeMap jfiles, put and get JFiles,
...)
class TextFile - fields and methods just for
TextFile (String contents, append )
- class Directory extends JFile // Java keyword
- Directory is a child of (inherits from) (is a
subclass of) JFile - Children do what their parents do - but more and
better - Parents may have children with different
behaviors - These are not box-and-arrow pictures (they show
methods)!
14Boxes and arrows
JFile/TextFile
JFile/Directory
String
String
owner
owner
Date
Date
createDate
createDate
Date
Date
modDate
modDate
Directory
Directory
parent
parent
String
TreeMap
contents
jfiles
15Design problem
- HLine and VLine each have length, paintChar, with
setters and getters - Box and Frame each have width, height, paintChar,
with setters and getters - Every shape has a paintOn method, but each kind
of shape paints itself differently - Can we write these classes without copying code?
- Yes (you will do it for hw5)
16Inheritance
class Object
abstract class Shape fields and methods needed
by all child classes (paintChar, getter and
setter, paintOn(Screen))
abstract class Rectangle - fields and methods for
rectangles (length, width)
abstract class XLine fields and methods for
lines (length, getLength, setLength)
class HLine paintOn(Screen,int,int)
class Box
class Frame
class Shape // extends Object
class VLine paintOn(Screen,int,int)
class XLine extends Shape
class HLine extends XLine
17How inheritance works
- Shape foo new HLine( 3, y)
- Variable foo declared of type Shape can have a
value thats a reference to an instance of some
child of Shape - Shape foo new Shape() not legal since Shape is
abstract - foo.setPaintChar(z)
- Send setPaintChar message to Shape foo,
which happens to be an HLine - Java looks for setPaintChar method in class Hline
- Not there! So looks in parent class XLine
- Not there! So looks in parent class Shape
- Found it! So search stops
18How inheritance works
- Screen s new Screen(5, 4)
- foo.paintOn(s)
- Send paintOn message to Shape foo,
which happens to be an HLine - No paintOn(Screen) in class HLine or class XLine
- Java finds paintOn(Screen) in class Shape
(eventually) - paintOn(Screen) delegates to paintOn(Screen, int,
int) - paintOn(Screen, int, int) is abstract in class
Shape - Java finds implementation in class HLine
19Design problem
- Directory should store TextFiles and Directories
- Directory and TextFile both have
- owner, create/mod date (same meaning)
- size, contents (different meanings)
- Directory has methods to add to, get from and
loop on its contents (the TreeMap of files in it) - TextFile has methods to manipulate its text
- Can we write these classes without copying code?
20Inheritance
class Object
class JFile - fields and methods needed by all
child classes (deal with owner and Dates),
abstract getSize method
class TextFile - fields and methods just for
TextFile (String contents, append )
class Directory - fields and methods just for
Directory (TreeMap jfiles, put and get JFiles,
...)
21Trees
- Common in computer science
- Java class hierarchy (shows inheritance)
- Unix (and Windows) tree for files and directories
- Vocabulary Tree, hierarchy
- Root (often drawn at the top!)
- Child, parent, branch, leaf, node
- Draw with arrows, or in outline form
22JFile system uses two trees
Java class hierarchy
Directory and TextFile hierarchy
class Object
root
eb
hello
class JFile
insult
cs110
diary
bill
class Directory
class TextFile
23JFile (easy part)
- private fields for
- String name Date createDate
- String owner Date modDate
- getters and setters as appropriate
- abstract getSize method since each child must
provide its own implementation - number of JFiles in a Directory
- number of characters in a TextFile
- main for unit testing
- 1/4 of the source code
- tedious but straightforward read it now
24Testing JFile, Directory, TextFile
- JFile has static code for testing
- public static main
- private static methods out, ls, cat
- private static field for Terminal
(visible in all static
methods) - main builds a tree of JFiles
- documented on lines 181-188
- constructed on lines 189-202
- explored on lines 204-223
25Look at ls
- ls is passed a Directory to list we might have
put ls in class Directory and asked a Directory
to list itself. We didnt, because Directory
knows nothing about printing. Client sends a
getContents message instead, and does its own
printing - The idiom test ? yes no
- loop on contents (like unit test in hw4)
- line 238 jfile.getSuffix
- Send a message to a JFile object without knowing
whether its a TextFile or a Directory
26Polymorphism poly (many) morph (shape)
- Directory.java
- maintains a list of JFile objects
- client retrieves them and sends them messages
- without knowing what kinds of JFiles they are!
- Client refers to objects of type Parent that are
really instances of a Child extending Parent - Powerful design tool - ignorance is bliss
27JFile getSuffix
- ls -f on mars appends
- / for directory listing (e.g. hw5 in cs110)
- _at_ for symbolic link (e.g. cs110 in your home)
- for an executable file (e.g. mkdir in /bin)
- (on Unix many commands are really files)
- no suffix for ordinary text files, class files,
... - We want JFiles to behave this way
- Ask a JFile to tell you its suffix by sending it
a getSuffix message - getSuffix is abstract in JFile.java
28\ vs /
- Windows uses one, Unix the other
- Java knows about both
- File.java (in the Java API) declares
public static final String separator - JFile.java declares
public static String separator
File.separator
29Managing the JFile tree
- A Directory
- keeps a TreeMap of JFiles
(the Directorys jfile
field)
keyed by name - has methods to add and retrieve JFiles by name
- has a method that allows client to loop on
contents - A JFile has a parent field in which it keeps a
reference to the Directory it belongs to (like
BankAccount Bank)
30JFile constructor
- JFile.java, line 50
- protected visible to children, not public
- lines 52-53 are easy they initialize fields
- if (parent ! null) (line 54)
- parent.addJFile( name, this )
- if this JFile has a parent (not top of JFile
tree) send message to parent to add this JFile
(Directory or TextFile) to its TreeMap,
with name as key. (Directory.java
line 69) - Careful parent directory ! parent class
31Constructors in a subclass
- Client creates a Directory with a name, an owner
and in a particular directory (like mkdir)
JFile.java line 236 - Directory cs110
new Directory(cs110, eb, home1) - Directory.java constructor
- line 34 initialize TreeMap declared on 21
(familiar from Chapter 4, hw4) - line 33 invoke parent class (JFile) constructor
(java keyword super is my parent)