36
Chapter 5 Generic Programming Anshuman Razdan Div of Computing Studies [email protected] http://dcst2.east.asu.edu/ ~razdan/cst230/

Chapter 5 Generic Programming Anshuman Razdan Div of Computing Studies [email protected] razdan/cst230

Embed Size (px)

Citation preview

Page 1: Chapter 5 Generic Programming Anshuman Razdan Div of Computing Studies razdan@asu.edu razdan/cst230

Chapter 5 Generic Programming

Anshuman RazdanDiv of Computing Studies

razdanasueduhttpdcst2eastasuedu~razdancst230

CET230 -- Razdan et al 2

Javarsquos Object typebull Java has 8 primitive types byte short int

long float double char boolean

bull Everything else is an Object

bull An ADT should be designed so that it can hold anything rather than specific typesndash Eg we made a list that could hold integers ndash

what if we need a list of strings or floats or students (from some Student class)hellip

ndash It would be better to make a list of Objects then we could put anything in the list

CET230 -- Razdan et al 3

Issues for ADT that hold objects

bull Class name should be arbitrary (not tied to a type Eg use Bag not IntBag)

bull Type of the underlying element is Object

bull Equality test should use equals not == or =

bull Decide how to deal with null references ndash can they be elements in the ADT

CET230 -- Razdan et al 4

Widening Conversions

bull If x and y are reference variables x=y is a widening conversion if the data type of x is capable of referring to a wider variety of things than the type of y

bull EgIntBag B = new IntBag()Object objobj = B

bull Java allows all widening conversions

CET230 -- Razdan et al 5

Narrowing Conversions

bull If x and y are reference variables x=y is a narrowing conversion if x has a smaller ability to refer to things than y

bull Eg Object obj = new IntBag()

IntBag B

B = obj

By using a typecast Java will allow all narrowing conversions (a ClassCastException could be thrown if conversion is ldquoillegalrdquo)

CET230 -- Razdan et al 6

Wrapper Classes

bull A wrapper class is a class in which each object holds a primitive classndash Byte Short Integer Long Float Double

Character Boolean are wrapper classesndash Accessor methods xxxValue() where xxx is

primitive type

bull Note Java 15 provides ldquoauto-boxingrdquo which replaces need for Accessor methods

CET230 -- Razdan et al 7

Old vs Newbull Wrappers bull Boxing

ObjList L = new ObjList() must put primitive value 3 into an object (box it) in order to have an object to insert in the listLinsert( new Integer(3) )hellipInteger num = (Integer)LgetHead() now we must ldquoun-boxrdquo the primitive value int i = numintValue()

ObjList L = new ObjList() Java 15 will auto-boxLinsert( 3 )hellip Java 15 will auto-unboxint I = LgetHead()

bullSee httpjavasuncomj2se150docsguidelanguageautoboxinghtmlfor discussion on autoboxing

CET230 -- Razdan et al 8

Clones amp Deep Clonesbull Consider the following codeclass Node implements Cloneable private Object data private Node next

public Object clone() Node nodeClone try nodeClone = (Node) superclone() catch( CloneNotSupportedException e)

CET230 -- Razdan et al 9

Fix (kinda) previousbull The previous example is a ldquoshallowrdquo clone

bull Fix the code to make a deep(er) cloneclass Node implements Cloneable Object data Node next public Object clone() Node nodeClone try nodeClone = (Node) superclone() catch( CloneNotSupportedException e) nodeClonesetData( thisdata )

nodeClonesetNext( )

CET230 -- Razdan et al 10

Really fix the shallow clonebull We still have a problem with the previous code

Nodes hold Object so clones are referencing the same data

bull What wersquod like to do is

bull But this has a problemndash We donrsquot know the actual class that ldquodatardquo belongs to ndash

it might not be Cloneable

bull To fix this check if ldquodatardquo is instanceof Cloneable If so we can do the ldquodeeprdquo clone If not then wersquore stuck with referencing the same ldquodatardquo object

nodeClonesetData(thisgetData()clone())

CET230 -- Razdan et al 11

List clone can use Node clonebull If a Node is Cloneable then the List clone

is pretty easy (all the work is done by the Node)

bull Consider the following (for List clone)

listClonehead = (Node) thisheadclone()

bull Now we just need to set listClonetail How about the followinglistClonetail = (Node) thistailclone()

bull What can we do

CET230 -- Razdan et al 12

Doubly Linked Listbull A doubly linked list allows us to store

references to the next node as well as the previous node

3 2 7 11

headtail

CET230 -- Razdan et al 13

Inheritance

bull A Doubly Linked List ldquois-ardquo List So we should take advantage of the List wersquove already implementedndash DoubleNode extends Nodendash DoubleList extends List

CET230 -- Razdan et al 14

Other Lists

bull Other types of lists are usefulndash Ordered list (elements in list are stored in some

order) Eg numbers are in increasing order strings are in alphabetical order etc

ndash Circular List the ldquoendrdquo of the list refers back to the head

ndash Skip Lists

CET230 -- Razdan et al 15

SkipList example from httpepaperpresscom

CET230 -- Razdan et al 16

Abstract Classesbull A robust implementation for List is to have an

ldquoAbstractListrdquo class from which concrete Lists (Singly Linked Doubly Linked Ordered etc) can be derived

bull An abstract classndash Has at least one abstract method (a method whose

interface is defined but NO implementation is specified by the class)

ndash Cannot be instantiatedndash Can provide implementation for some methodsndash Can provide attributes common to all concrete

subclasses

CET230 -- Razdan et al 17

Abstract List

bull Attributesndash head tail length

bull Methodsndash Constructor getLength equals clone

bull Abstract Methodsndash Add remove clone

CET230 -- Razdan et al 18

Implement clone in AbstractList

bull What Irsquod really like is to implement the clone() in the AbstractList classndash All Lists contain Nodes We donrsquot want to

rewrite the same code for the clone method over and over again in the concrete List classes

ndash Problem what about a DoubleList that contains DoubleNode The AbstractList implementation will not do enoughbecause the Node clone does not do enough

ndash But I WANT it to do enough

CET230 -- Razdan et al 19

Reflectionbull What if we made the Node clone ldquosmarterrdquo

ndash if itrsquos just a Node then do a Node clonendash if itrsquos some other kind of Node then do that

clonendash But the Node doesnrsquot know all the other classes

that extend it

bull Reflection can be used to obtain information about a class its members or its methods

CET230 -- Razdan et al 20

Reflection cont

bull The Class class (see javalang) has methods that enable us to get information about the classndash eg getMethod(String name Class

[] parameterTypes) returns ldquoMethodrdquo

bull The Method class (see javalangreflect) has methods that enable us to get information about the Method and even CALL the methodndash Object invoke(Object obj Object[] args)

CET230 -- Razdan et al 21

ldquoBionicrdquo Nodebull We can modify the Node clone as follows

Node nodeClonetry nodeClone = (Node) superclone() catch( CloneNotSupportedException e ) throw new CloneNotSupportedException()if( thisdata instanceof Cloneable ) try Class c = thisdatagetClass() Method m = cgetMethod( clone null )

nodeClonedata = minvoke( thisdata null ) catch( Exception e ) nodeClonedata = thisdata else nodeClonedata = thisdataif( thisnext = null ) nodeClonenext = (Node) thisnextclone()else nodeClonenext = nullreturn( nodeClone )

CET230 -- Razdan et al 22

Revisiting the String classbull Some useful String methods

ndash charAt( int index)

ndash indexOf( char ch )

ndash indexOf( String str )

ndash split( String regex )

ndash startsWith( String prefix )

ndash substring( int beginIndex int endIndex )

ndash toLowerCase()

ndash toUpperCase()

Note StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code It is recommended that anyone seeking this functionality use the split method of String or the javautilregex package instead

CET230 -- Razdan et al 23

Using Files for IObull Using files for IO is similar to standard IObull For standard input you usually use

ndash InputStreamReaderndash BufferedReader

bull For standard output you usually usendash Systemoutprint or println

bull For file input you can usendash FileReaderndash BufferedReader

bull For file output you can usendash FileWriterndash BufferedWriter

CET230 -- Razdan et al 24

FileReader constructorFileReader

public FileReader(String fileName) throws FileNotFoundException

Creates a new FileReader given the name of the file to read from

Parameters fileName - the name of the file to read from

Throws FileNotFoundException - if the named file does not exist is a directory rather than a regular file or for some other reason cannot be opened for reading

CET230 -- Razdan et al 25

Read ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )

String s = inreadLine()int i = 1while( s = null )

Systemoutprintln(ldquoLine ldquo + i + ldquo ldquo + s )

i++s = inreadLine()

inclose()

CET230 -- Razdan et al 26

FileWriter constructor

FileWriter

public FileWriter(String fileName) throws IOException Constructs a FileWriter object given a file name

Parameters fileName - String The system-dependent filename

Throws IOException - if the named file exists but is a directory rather than a regular file does not exist but cannot be created or cannot be opened for any other reason

CET230 -- Razdan et al 27

BufferedWriter

Method Summary void

close() Close the stream

voidflush() Flush the stream

voidnewLine() Write a line separator

voidwrite(char[] cbuf int off int len) Write a portion of an array of characters

voidwrite(int c) Write a single character

voidwrite(String s int off int len) Write a portion of a String

CET230 -- Razdan et al 28

Write ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )BufferedWriter out = new BufferedWriter(

new FileWriter(outfile) )

String s = inreadLine()while( s = null )

outwrite((ssplit(ldquosrdquo))[0])outnewLine()s = inreadLine()

inclose()outclose()

CET230 -- Razdan et al 29

Java Interfaces

bull A Java interface is a set of related methods that a programmer may want to support in a single classndash Eg Cloneablendash Eg Comparablehttpjavasuncomj2se150docsapijavalangComparablehtml

CET230 -- Razdan et al 30

Iterator Pattern

bull Motivation ndash an aggregate object should give you a way to access its

elements without exposing its internal structure

ndash Use of the object may want to traverse the object in many different ways ndash donrsquot want to bloat the interface with may traversal methods even if you could anticipate all the methods needed

ndash May need to have more than one traversal pending on the aggregate at once

CET230 -- Razdan et al 31

Iterator Patternbull Key idea take responsibility for access and

traversal out of the object and put it into an iterator object

bull Iterator provides basic ldquonavigationrdquo methods eg ndash Firstndash Nextndash IsDonendash CurrentItem

CET230 -- Razdan et al 32

Map Interface

bull A map is a collection class in which keyvalue pairs may be added A pair can be retrieved or removed by specifying just its key

CET230 -- Razdan et al 33

TreeMap

bull Javarsquos TreeMapltK Vgt implements the map interface in an efficient way in which the keys are required to come from a class (such as String) that implements the Comparable interface

CET230 -- Razdan et al 34

Example

bull From package javautil

bull TreeMapltString Integergt frequencyData

bull String word

bull Integer count

CET230 -- Razdan et al 35

Operations

bull public V get(K key)

bull public V put(K key V value)

bull public boolean containsKey(K key)

bull public SetltKgt keySet()

bull public int size()

bull public void clear()

CET230 -- Razdan et al 36

Iteration

for (String word wordMapkeySet())

hellipprocess this key which is in variable wordhellip

  • Chapter 5 Generic Programming
  • Javarsquos Object type
  • Issues for ADT that hold objects
  • Widening Conversions
  • Narrowing Conversions
  • Wrapper Classes
  • Old vs New
  • Clones amp Deep Clones
  • Fix (kinda) previous
  • Really fix the shallow clone
  • List clone can use Node clone
  • Doubly Linked List
  • Inheritance
  • Other Lists
  • SkipList example from httpepaperpresscom
  • Abstract Classes
  • Abstract List
  • Implement clone in AbstractList
  • Reflection
  • Reflection cont
  • ldquoBionicrdquo Node
  • Revisiting the String class
  • Using Files for IO
  • FileReader constructor
  • Read Example
  • FileWriter constructor
  • BufferedWriter
  • Write Example
  • Java Interfaces
  • Iterator Pattern
  • Slide 31
  • Map Interface
  • TreeMap
  • Example
  • Operations
  • Iteration
Page 2: Chapter 5 Generic Programming Anshuman Razdan Div of Computing Studies razdan@asu.edu razdan/cst230

CET230 -- Razdan et al 2

Javarsquos Object typebull Java has 8 primitive types byte short int

long float double char boolean

bull Everything else is an Object

bull An ADT should be designed so that it can hold anything rather than specific typesndash Eg we made a list that could hold integers ndash

what if we need a list of strings or floats or students (from some Student class)hellip

ndash It would be better to make a list of Objects then we could put anything in the list

CET230 -- Razdan et al 3

Issues for ADT that hold objects

bull Class name should be arbitrary (not tied to a type Eg use Bag not IntBag)

bull Type of the underlying element is Object

bull Equality test should use equals not == or =

bull Decide how to deal with null references ndash can they be elements in the ADT

CET230 -- Razdan et al 4

Widening Conversions

bull If x and y are reference variables x=y is a widening conversion if the data type of x is capable of referring to a wider variety of things than the type of y

bull EgIntBag B = new IntBag()Object objobj = B

bull Java allows all widening conversions

CET230 -- Razdan et al 5

Narrowing Conversions

bull If x and y are reference variables x=y is a narrowing conversion if x has a smaller ability to refer to things than y

bull Eg Object obj = new IntBag()

IntBag B

B = obj

By using a typecast Java will allow all narrowing conversions (a ClassCastException could be thrown if conversion is ldquoillegalrdquo)

CET230 -- Razdan et al 6

Wrapper Classes

bull A wrapper class is a class in which each object holds a primitive classndash Byte Short Integer Long Float Double

Character Boolean are wrapper classesndash Accessor methods xxxValue() where xxx is

primitive type

bull Note Java 15 provides ldquoauto-boxingrdquo which replaces need for Accessor methods

CET230 -- Razdan et al 7

Old vs Newbull Wrappers bull Boxing

ObjList L = new ObjList() must put primitive value 3 into an object (box it) in order to have an object to insert in the listLinsert( new Integer(3) )hellipInteger num = (Integer)LgetHead() now we must ldquoun-boxrdquo the primitive value int i = numintValue()

ObjList L = new ObjList() Java 15 will auto-boxLinsert( 3 )hellip Java 15 will auto-unboxint I = LgetHead()

bullSee httpjavasuncomj2se150docsguidelanguageautoboxinghtmlfor discussion on autoboxing

CET230 -- Razdan et al 8

Clones amp Deep Clonesbull Consider the following codeclass Node implements Cloneable private Object data private Node next

public Object clone() Node nodeClone try nodeClone = (Node) superclone() catch( CloneNotSupportedException e)

CET230 -- Razdan et al 9

Fix (kinda) previousbull The previous example is a ldquoshallowrdquo clone

bull Fix the code to make a deep(er) cloneclass Node implements Cloneable Object data Node next public Object clone() Node nodeClone try nodeClone = (Node) superclone() catch( CloneNotSupportedException e) nodeClonesetData( thisdata )

nodeClonesetNext( )

CET230 -- Razdan et al 10

Really fix the shallow clonebull We still have a problem with the previous code

Nodes hold Object so clones are referencing the same data

bull What wersquod like to do is

bull But this has a problemndash We donrsquot know the actual class that ldquodatardquo belongs to ndash

it might not be Cloneable

bull To fix this check if ldquodatardquo is instanceof Cloneable If so we can do the ldquodeeprdquo clone If not then wersquore stuck with referencing the same ldquodatardquo object

nodeClonesetData(thisgetData()clone())

CET230 -- Razdan et al 11

List clone can use Node clonebull If a Node is Cloneable then the List clone

is pretty easy (all the work is done by the Node)

bull Consider the following (for List clone)

listClonehead = (Node) thisheadclone()

bull Now we just need to set listClonetail How about the followinglistClonetail = (Node) thistailclone()

bull What can we do

CET230 -- Razdan et al 12

Doubly Linked Listbull A doubly linked list allows us to store

references to the next node as well as the previous node

3 2 7 11

headtail

CET230 -- Razdan et al 13

Inheritance

bull A Doubly Linked List ldquois-ardquo List So we should take advantage of the List wersquove already implementedndash DoubleNode extends Nodendash DoubleList extends List

CET230 -- Razdan et al 14

Other Lists

bull Other types of lists are usefulndash Ordered list (elements in list are stored in some

order) Eg numbers are in increasing order strings are in alphabetical order etc

ndash Circular List the ldquoendrdquo of the list refers back to the head

ndash Skip Lists

CET230 -- Razdan et al 15

SkipList example from httpepaperpresscom

CET230 -- Razdan et al 16

Abstract Classesbull A robust implementation for List is to have an

ldquoAbstractListrdquo class from which concrete Lists (Singly Linked Doubly Linked Ordered etc) can be derived

bull An abstract classndash Has at least one abstract method (a method whose

interface is defined but NO implementation is specified by the class)

ndash Cannot be instantiatedndash Can provide implementation for some methodsndash Can provide attributes common to all concrete

subclasses

CET230 -- Razdan et al 17

Abstract List

bull Attributesndash head tail length

bull Methodsndash Constructor getLength equals clone

bull Abstract Methodsndash Add remove clone

CET230 -- Razdan et al 18

Implement clone in AbstractList

bull What Irsquod really like is to implement the clone() in the AbstractList classndash All Lists contain Nodes We donrsquot want to

rewrite the same code for the clone method over and over again in the concrete List classes

ndash Problem what about a DoubleList that contains DoubleNode The AbstractList implementation will not do enoughbecause the Node clone does not do enough

ndash But I WANT it to do enough

CET230 -- Razdan et al 19

Reflectionbull What if we made the Node clone ldquosmarterrdquo

ndash if itrsquos just a Node then do a Node clonendash if itrsquos some other kind of Node then do that

clonendash But the Node doesnrsquot know all the other classes

that extend it

bull Reflection can be used to obtain information about a class its members or its methods

CET230 -- Razdan et al 20

Reflection cont

bull The Class class (see javalang) has methods that enable us to get information about the classndash eg getMethod(String name Class

[] parameterTypes) returns ldquoMethodrdquo

bull The Method class (see javalangreflect) has methods that enable us to get information about the Method and even CALL the methodndash Object invoke(Object obj Object[] args)

CET230 -- Razdan et al 21

ldquoBionicrdquo Nodebull We can modify the Node clone as follows

Node nodeClonetry nodeClone = (Node) superclone() catch( CloneNotSupportedException e ) throw new CloneNotSupportedException()if( thisdata instanceof Cloneable ) try Class c = thisdatagetClass() Method m = cgetMethod( clone null )

nodeClonedata = minvoke( thisdata null ) catch( Exception e ) nodeClonedata = thisdata else nodeClonedata = thisdataif( thisnext = null ) nodeClonenext = (Node) thisnextclone()else nodeClonenext = nullreturn( nodeClone )

CET230 -- Razdan et al 22

Revisiting the String classbull Some useful String methods

ndash charAt( int index)

ndash indexOf( char ch )

ndash indexOf( String str )

ndash split( String regex )

ndash startsWith( String prefix )

ndash substring( int beginIndex int endIndex )

ndash toLowerCase()

ndash toUpperCase()

Note StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code It is recommended that anyone seeking this functionality use the split method of String or the javautilregex package instead

CET230 -- Razdan et al 23

Using Files for IObull Using files for IO is similar to standard IObull For standard input you usually use

ndash InputStreamReaderndash BufferedReader

bull For standard output you usually usendash Systemoutprint or println

bull For file input you can usendash FileReaderndash BufferedReader

bull For file output you can usendash FileWriterndash BufferedWriter

CET230 -- Razdan et al 24

FileReader constructorFileReader

public FileReader(String fileName) throws FileNotFoundException

Creates a new FileReader given the name of the file to read from

Parameters fileName - the name of the file to read from

Throws FileNotFoundException - if the named file does not exist is a directory rather than a regular file or for some other reason cannot be opened for reading

CET230 -- Razdan et al 25

Read ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )

String s = inreadLine()int i = 1while( s = null )

Systemoutprintln(ldquoLine ldquo + i + ldquo ldquo + s )

i++s = inreadLine()

inclose()

CET230 -- Razdan et al 26

FileWriter constructor

FileWriter

public FileWriter(String fileName) throws IOException Constructs a FileWriter object given a file name

Parameters fileName - String The system-dependent filename

Throws IOException - if the named file exists but is a directory rather than a regular file does not exist but cannot be created or cannot be opened for any other reason

CET230 -- Razdan et al 27

BufferedWriter

Method Summary void

close() Close the stream

voidflush() Flush the stream

voidnewLine() Write a line separator

voidwrite(char[] cbuf int off int len) Write a portion of an array of characters

voidwrite(int c) Write a single character

voidwrite(String s int off int len) Write a portion of a String

CET230 -- Razdan et al 28

Write ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )BufferedWriter out = new BufferedWriter(

new FileWriter(outfile) )

String s = inreadLine()while( s = null )

outwrite((ssplit(ldquosrdquo))[0])outnewLine()s = inreadLine()

inclose()outclose()

CET230 -- Razdan et al 29

Java Interfaces

bull A Java interface is a set of related methods that a programmer may want to support in a single classndash Eg Cloneablendash Eg Comparablehttpjavasuncomj2se150docsapijavalangComparablehtml

CET230 -- Razdan et al 30

Iterator Pattern

bull Motivation ndash an aggregate object should give you a way to access its

elements without exposing its internal structure

ndash Use of the object may want to traverse the object in many different ways ndash donrsquot want to bloat the interface with may traversal methods even if you could anticipate all the methods needed

ndash May need to have more than one traversal pending on the aggregate at once

CET230 -- Razdan et al 31

Iterator Patternbull Key idea take responsibility for access and

traversal out of the object and put it into an iterator object

bull Iterator provides basic ldquonavigationrdquo methods eg ndash Firstndash Nextndash IsDonendash CurrentItem

CET230 -- Razdan et al 32

Map Interface

bull A map is a collection class in which keyvalue pairs may be added A pair can be retrieved or removed by specifying just its key

CET230 -- Razdan et al 33

TreeMap

bull Javarsquos TreeMapltK Vgt implements the map interface in an efficient way in which the keys are required to come from a class (such as String) that implements the Comparable interface

CET230 -- Razdan et al 34

Example

bull From package javautil

bull TreeMapltString Integergt frequencyData

bull String word

bull Integer count

CET230 -- Razdan et al 35

Operations

bull public V get(K key)

bull public V put(K key V value)

bull public boolean containsKey(K key)

bull public SetltKgt keySet()

bull public int size()

bull public void clear()

CET230 -- Razdan et al 36

Iteration

for (String word wordMapkeySet())

hellipprocess this key which is in variable wordhellip

  • Chapter 5 Generic Programming
  • Javarsquos Object type
  • Issues for ADT that hold objects
  • Widening Conversions
  • Narrowing Conversions
  • Wrapper Classes
  • Old vs New
  • Clones amp Deep Clones
  • Fix (kinda) previous
  • Really fix the shallow clone
  • List clone can use Node clone
  • Doubly Linked List
  • Inheritance
  • Other Lists
  • SkipList example from httpepaperpresscom
  • Abstract Classes
  • Abstract List
  • Implement clone in AbstractList
  • Reflection
  • Reflection cont
  • ldquoBionicrdquo Node
  • Revisiting the String class
  • Using Files for IO
  • FileReader constructor
  • Read Example
  • FileWriter constructor
  • BufferedWriter
  • Write Example
  • Java Interfaces
  • Iterator Pattern
  • Slide 31
  • Map Interface
  • TreeMap
  • Example
  • Operations
  • Iteration
Page 3: Chapter 5 Generic Programming Anshuman Razdan Div of Computing Studies razdan@asu.edu razdan/cst230

CET230 -- Razdan et al 3

Issues for ADT that hold objects

bull Class name should be arbitrary (not tied to a type Eg use Bag not IntBag)

bull Type of the underlying element is Object

bull Equality test should use equals not == or =

bull Decide how to deal with null references ndash can they be elements in the ADT

CET230 -- Razdan et al 4

Widening Conversions

bull If x and y are reference variables x=y is a widening conversion if the data type of x is capable of referring to a wider variety of things than the type of y

bull EgIntBag B = new IntBag()Object objobj = B

bull Java allows all widening conversions

CET230 -- Razdan et al 5

Narrowing Conversions

bull If x and y are reference variables x=y is a narrowing conversion if x has a smaller ability to refer to things than y

bull Eg Object obj = new IntBag()

IntBag B

B = obj

By using a typecast Java will allow all narrowing conversions (a ClassCastException could be thrown if conversion is ldquoillegalrdquo)

CET230 -- Razdan et al 6

Wrapper Classes

bull A wrapper class is a class in which each object holds a primitive classndash Byte Short Integer Long Float Double

Character Boolean are wrapper classesndash Accessor methods xxxValue() where xxx is

primitive type

bull Note Java 15 provides ldquoauto-boxingrdquo which replaces need for Accessor methods

CET230 -- Razdan et al 7

Old vs Newbull Wrappers bull Boxing

ObjList L = new ObjList() must put primitive value 3 into an object (box it) in order to have an object to insert in the listLinsert( new Integer(3) )hellipInteger num = (Integer)LgetHead() now we must ldquoun-boxrdquo the primitive value int i = numintValue()

ObjList L = new ObjList() Java 15 will auto-boxLinsert( 3 )hellip Java 15 will auto-unboxint I = LgetHead()

bullSee httpjavasuncomj2se150docsguidelanguageautoboxinghtmlfor discussion on autoboxing

CET230 -- Razdan et al 8

Clones amp Deep Clonesbull Consider the following codeclass Node implements Cloneable private Object data private Node next

public Object clone() Node nodeClone try nodeClone = (Node) superclone() catch( CloneNotSupportedException e)

CET230 -- Razdan et al 9

Fix (kinda) previousbull The previous example is a ldquoshallowrdquo clone

bull Fix the code to make a deep(er) cloneclass Node implements Cloneable Object data Node next public Object clone() Node nodeClone try nodeClone = (Node) superclone() catch( CloneNotSupportedException e) nodeClonesetData( thisdata )

nodeClonesetNext( )

CET230 -- Razdan et al 10

Really fix the shallow clonebull We still have a problem with the previous code

Nodes hold Object so clones are referencing the same data

bull What wersquod like to do is

bull But this has a problemndash We donrsquot know the actual class that ldquodatardquo belongs to ndash

it might not be Cloneable

bull To fix this check if ldquodatardquo is instanceof Cloneable If so we can do the ldquodeeprdquo clone If not then wersquore stuck with referencing the same ldquodatardquo object

nodeClonesetData(thisgetData()clone())

CET230 -- Razdan et al 11

List clone can use Node clonebull If a Node is Cloneable then the List clone

is pretty easy (all the work is done by the Node)

bull Consider the following (for List clone)

listClonehead = (Node) thisheadclone()

bull Now we just need to set listClonetail How about the followinglistClonetail = (Node) thistailclone()

bull What can we do

CET230 -- Razdan et al 12

Doubly Linked Listbull A doubly linked list allows us to store

references to the next node as well as the previous node

3 2 7 11

headtail

CET230 -- Razdan et al 13

Inheritance

bull A Doubly Linked List ldquois-ardquo List So we should take advantage of the List wersquove already implementedndash DoubleNode extends Nodendash DoubleList extends List

CET230 -- Razdan et al 14

Other Lists

bull Other types of lists are usefulndash Ordered list (elements in list are stored in some

order) Eg numbers are in increasing order strings are in alphabetical order etc

ndash Circular List the ldquoendrdquo of the list refers back to the head

ndash Skip Lists

CET230 -- Razdan et al 15

SkipList example from httpepaperpresscom

CET230 -- Razdan et al 16

Abstract Classesbull A robust implementation for List is to have an

ldquoAbstractListrdquo class from which concrete Lists (Singly Linked Doubly Linked Ordered etc) can be derived

bull An abstract classndash Has at least one abstract method (a method whose

interface is defined but NO implementation is specified by the class)

ndash Cannot be instantiatedndash Can provide implementation for some methodsndash Can provide attributes common to all concrete

subclasses

CET230 -- Razdan et al 17

Abstract List

bull Attributesndash head tail length

bull Methodsndash Constructor getLength equals clone

bull Abstract Methodsndash Add remove clone

CET230 -- Razdan et al 18

Implement clone in AbstractList

bull What Irsquod really like is to implement the clone() in the AbstractList classndash All Lists contain Nodes We donrsquot want to

rewrite the same code for the clone method over and over again in the concrete List classes

ndash Problem what about a DoubleList that contains DoubleNode The AbstractList implementation will not do enoughbecause the Node clone does not do enough

ndash But I WANT it to do enough

CET230 -- Razdan et al 19

Reflectionbull What if we made the Node clone ldquosmarterrdquo

ndash if itrsquos just a Node then do a Node clonendash if itrsquos some other kind of Node then do that

clonendash But the Node doesnrsquot know all the other classes

that extend it

bull Reflection can be used to obtain information about a class its members or its methods

CET230 -- Razdan et al 20

Reflection cont

bull The Class class (see javalang) has methods that enable us to get information about the classndash eg getMethod(String name Class

[] parameterTypes) returns ldquoMethodrdquo

bull The Method class (see javalangreflect) has methods that enable us to get information about the Method and even CALL the methodndash Object invoke(Object obj Object[] args)

CET230 -- Razdan et al 21

ldquoBionicrdquo Nodebull We can modify the Node clone as follows

Node nodeClonetry nodeClone = (Node) superclone() catch( CloneNotSupportedException e ) throw new CloneNotSupportedException()if( thisdata instanceof Cloneable ) try Class c = thisdatagetClass() Method m = cgetMethod( clone null )

nodeClonedata = minvoke( thisdata null ) catch( Exception e ) nodeClonedata = thisdata else nodeClonedata = thisdataif( thisnext = null ) nodeClonenext = (Node) thisnextclone()else nodeClonenext = nullreturn( nodeClone )

CET230 -- Razdan et al 22

Revisiting the String classbull Some useful String methods

ndash charAt( int index)

ndash indexOf( char ch )

ndash indexOf( String str )

ndash split( String regex )

ndash startsWith( String prefix )

ndash substring( int beginIndex int endIndex )

ndash toLowerCase()

ndash toUpperCase()

Note StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code It is recommended that anyone seeking this functionality use the split method of String or the javautilregex package instead

CET230 -- Razdan et al 23

Using Files for IObull Using files for IO is similar to standard IObull For standard input you usually use

ndash InputStreamReaderndash BufferedReader

bull For standard output you usually usendash Systemoutprint or println

bull For file input you can usendash FileReaderndash BufferedReader

bull For file output you can usendash FileWriterndash BufferedWriter

CET230 -- Razdan et al 24

FileReader constructorFileReader

public FileReader(String fileName) throws FileNotFoundException

Creates a new FileReader given the name of the file to read from

Parameters fileName - the name of the file to read from

Throws FileNotFoundException - if the named file does not exist is a directory rather than a regular file or for some other reason cannot be opened for reading

CET230 -- Razdan et al 25

Read ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )

String s = inreadLine()int i = 1while( s = null )

Systemoutprintln(ldquoLine ldquo + i + ldquo ldquo + s )

i++s = inreadLine()

inclose()

CET230 -- Razdan et al 26

FileWriter constructor

FileWriter

public FileWriter(String fileName) throws IOException Constructs a FileWriter object given a file name

Parameters fileName - String The system-dependent filename

Throws IOException - if the named file exists but is a directory rather than a regular file does not exist but cannot be created or cannot be opened for any other reason

CET230 -- Razdan et al 27

BufferedWriter

Method Summary void

close() Close the stream

voidflush() Flush the stream

voidnewLine() Write a line separator

voidwrite(char[] cbuf int off int len) Write a portion of an array of characters

voidwrite(int c) Write a single character

voidwrite(String s int off int len) Write a portion of a String

CET230 -- Razdan et al 28

Write ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )BufferedWriter out = new BufferedWriter(

new FileWriter(outfile) )

String s = inreadLine()while( s = null )

outwrite((ssplit(ldquosrdquo))[0])outnewLine()s = inreadLine()

inclose()outclose()

CET230 -- Razdan et al 29

Java Interfaces

bull A Java interface is a set of related methods that a programmer may want to support in a single classndash Eg Cloneablendash Eg Comparablehttpjavasuncomj2se150docsapijavalangComparablehtml

CET230 -- Razdan et al 30

Iterator Pattern

bull Motivation ndash an aggregate object should give you a way to access its

elements without exposing its internal structure

ndash Use of the object may want to traverse the object in many different ways ndash donrsquot want to bloat the interface with may traversal methods even if you could anticipate all the methods needed

ndash May need to have more than one traversal pending on the aggregate at once

CET230 -- Razdan et al 31

Iterator Patternbull Key idea take responsibility for access and

traversal out of the object and put it into an iterator object

bull Iterator provides basic ldquonavigationrdquo methods eg ndash Firstndash Nextndash IsDonendash CurrentItem

CET230 -- Razdan et al 32

Map Interface

bull A map is a collection class in which keyvalue pairs may be added A pair can be retrieved or removed by specifying just its key

CET230 -- Razdan et al 33

TreeMap

bull Javarsquos TreeMapltK Vgt implements the map interface in an efficient way in which the keys are required to come from a class (such as String) that implements the Comparable interface

CET230 -- Razdan et al 34

Example

bull From package javautil

bull TreeMapltString Integergt frequencyData

bull String word

bull Integer count

CET230 -- Razdan et al 35

Operations

bull public V get(K key)

bull public V put(K key V value)

bull public boolean containsKey(K key)

bull public SetltKgt keySet()

bull public int size()

bull public void clear()

CET230 -- Razdan et al 36

Iteration

for (String word wordMapkeySet())

hellipprocess this key which is in variable wordhellip

  • Chapter 5 Generic Programming
  • Javarsquos Object type
  • Issues for ADT that hold objects
  • Widening Conversions
  • Narrowing Conversions
  • Wrapper Classes
  • Old vs New
  • Clones amp Deep Clones
  • Fix (kinda) previous
  • Really fix the shallow clone
  • List clone can use Node clone
  • Doubly Linked List
  • Inheritance
  • Other Lists
  • SkipList example from httpepaperpresscom
  • Abstract Classes
  • Abstract List
  • Implement clone in AbstractList
  • Reflection
  • Reflection cont
  • ldquoBionicrdquo Node
  • Revisiting the String class
  • Using Files for IO
  • FileReader constructor
  • Read Example
  • FileWriter constructor
  • BufferedWriter
  • Write Example
  • Java Interfaces
  • Iterator Pattern
  • Slide 31
  • Map Interface
  • TreeMap
  • Example
  • Operations
  • Iteration
Page 4: Chapter 5 Generic Programming Anshuman Razdan Div of Computing Studies razdan@asu.edu razdan/cst230

CET230 -- Razdan et al 4

Widening Conversions

bull If x and y are reference variables x=y is a widening conversion if the data type of x is capable of referring to a wider variety of things than the type of y

bull EgIntBag B = new IntBag()Object objobj = B

bull Java allows all widening conversions

CET230 -- Razdan et al 5

Narrowing Conversions

bull If x and y are reference variables x=y is a narrowing conversion if x has a smaller ability to refer to things than y

bull Eg Object obj = new IntBag()

IntBag B

B = obj

By using a typecast Java will allow all narrowing conversions (a ClassCastException could be thrown if conversion is ldquoillegalrdquo)

CET230 -- Razdan et al 6

Wrapper Classes

bull A wrapper class is a class in which each object holds a primitive classndash Byte Short Integer Long Float Double

Character Boolean are wrapper classesndash Accessor methods xxxValue() where xxx is

primitive type

bull Note Java 15 provides ldquoauto-boxingrdquo which replaces need for Accessor methods

CET230 -- Razdan et al 7

Old vs Newbull Wrappers bull Boxing

ObjList L = new ObjList() must put primitive value 3 into an object (box it) in order to have an object to insert in the listLinsert( new Integer(3) )hellipInteger num = (Integer)LgetHead() now we must ldquoun-boxrdquo the primitive value int i = numintValue()

ObjList L = new ObjList() Java 15 will auto-boxLinsert( 3 )hellip Java 15 will auto-unboxint I = LgetHead()

bullSee httpjavasuncomj2se150docsguidelanguageautoboxinghtmlfor discussion on autoboxing

CET230 -- Razdan et al 8

Clones amp Deep Clonesbull Consider the following codeclass Node implements Cloneable private Object data private Node next

public Object clone() Node nodeClone try nodeClone = (Node) superclone() catch( CloneNotSupportedException e)

CET230 -- Razdan et al 9

Fix (kinda) previousbull The previous example is a ldquoshallowrdquo clone

bull Fix the code to make a deep(er) cloneclass Node implements Cloneable Object data Node next public Object clone() Node nodeClone try nodeClone = (Node) superclone() catch( CloneNotSupportedException e) nodeClonesetData( thisdata )

nodeClonesetNext( )

CET230 -- Razdan et al 10

Really fix the shallow clonebull We still have a problem with the previous code

Nodes hold Object so clones are referencing the same data

bull What wersquod like to do is

bull But this has a problemndash We donrsquot know the actual class that ldquodatardquo belongs to ndash

it might not be Cloneable

bull To fix this check if ldquodatardquo is instanceof Cloneable If so we can do the ldquodeeprdquo clone If not then wersquore stuck with referencing the same ldquodatardquo object

nodeClonesetData(thisgetData()clone())

CET230 -- Razdan et al 11

List clone can use Node clonebull If a Node is Cloneable then the List clone

is pretty easy (all the work is done by the Node)

bull Consider the following (for List clone)

listClonehead = (Node) thisheadclone()

bull Now we just need to set listClonetail How about the followinglistClonetail = (Node) thistailclone()

bull What can we do

CET230 -- Razdan et al 12

Doubly Linked Listbull A doubly linked list allows us to store

references to the next node as well as the previous node

3 2 7 11

headtail

CET230 -- Razdan et al 13

Inheritance

bull A Doubly Linked List ldquois-ardquo List So we should take advantage of the List wersquove already implementedndash DoubleNode extends Nodendash DoubleList extends List

CET230 -- Razdan et al 14

Other Lists

bull Other types of lists are usefulndash Ordered list (elements in list are stored in some

order) Eg numbers are in increasing order strings are in alphabetical order etc

ndash Circular List the ldquoendrdquo of the list refers back to the head

ndash Skip Lists

CET230 -- Razdan et al 15

SkipList example from httpepaperpresscom

CET230 -- Razdan et al 16

Abstract Classesbull A robust implementation for List is to have an

ldquoAbstractListrdquo class from which concrete Lists (Singly Linked Doubly Linked Ordered etc) can be derived

bull An abstract classndash Has at least one abstract method (a method whose

interface is defined but NO implementation is specified by the class)

ndash Cannot be instantiatedndash Can provide implementation for some methodsndash Can provide attributes common to all concrete

subclasses

CET230 -- Razdan et al 17

Abstract List

bull Attributesndash head tail length

bull Methodsndash Constructor getLength equals clone

bull Abstract Methodsndash Add remove clone

CET230 -- Razdan et al 18

Implement clone in AbstractList

bull What Irsquod really like is to implement the clone() in the AbstractList classndash All Lists contain Nodes We donrsquot want to

rewrite the same code for the clone method over and over again in the concrete List classes

ndash Problem what about a DoubleList that contains DoubleNode The AbstractList implementation will not do enoughbecause the Node clone does not do enough

ndash But I WANT it to do enough

CET230 -- Razdan et al 19

Reflectionbull What if we made the Node clone ldquosmarterrdquo

ndash if itrsquos just a Node then do a Node clonendash if itrsquos some other kind of Node then do that

clonendash But the Node doesnrsquot know all the other classes

that extend it

bull Reflection can be used to obtain information about a class its members or its methods

CET230 -- Razdan et al 20

Reflection cont

bull The Class class (see javalang) has methods that enable us to get information about the classndash eg getMethod(String name Class

[] parameterTypes) returns ldquoMethodrdquo

bull The Method class (see javalangreflect) has methods that enable us to get information about the Method and even CALL the methodndash Object invoke(Object obj Object[] args)

CET230 -- Razdan et al 21

ldquoBionicrdquo Nodebull We can modify the Node clone as follows

Node nodeClonetry nodeClone = (Node) superclone() catch( CloneNotSupportedException e ) throw new CloneNotSupportedException()if( thisdata instanceof Cloneable ) try Class c = thisdatagetClass() Method m = cgetMethod( clone null )

nodeClonedata = minvoke( thisdata null ) catch( Exception e ) nodeClonedata = thisdata else nodeClonedata = thisdataif( thisnext = null ) nodeClonenext = (Node) thisnextclone()else nodeClonenext = nullreturn( nodeClone )

CET230 -- Razdan et al 22

Revisiting the String classbull Some useful String methods

ndash charAt( int index)

ndash indexOf( char ch )

ndash indexOf( String str )

ndash split( String regex )

ndash startsWith( String prefix )

ndash substring( int beginIndex int endIndex )

ndash toLowerCase()

ndash toUpperCase()

Note StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code It is recommended that anyone seeking this functionality use the split method of String or the javautilregex package instead

CET230 -- Razdan et al 23

Using Files for IObull Using files for IO is similar to standard IObull For standard input you usually use

ndash InputStreamReaderndash BufferedReader

bull For standard output you usually usendash Systemoutprint or println

bull For file input you can usendash FileReaderndash BufferedReader

bull For file output you can usendash FileWriterndash BufferedWriter

CET230 -- Razdan et al 24

FileReader constructorFileReader

public FileReader(String fileName) throws FileNotFoundException

Creates a new FileReader given the name of the file to read from

Parameters fileName - the name of the file to read from

Throws FileNotFoundException - if the named file does not exist is a directory rather than a regular file or for some other reason cannot be opened for reading

CET230 -- Razdan et al 25

Read ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )

String s = inreadLine()int i = 1while( s = null )

Systemoutprintln(ldquoLine ldquo + i + ldquo ldquo + s )

i++s = inreadLine()

inclose()

CET230 -- Razdan et al 26

FileWriter constructor

FileWriter

public FileWriter(String fileName) throws IOException Constructs a FileWriter object given a file name

Parameters fileName - String The system-dependent filename

Throws IOException - if the named file exists but is a directory rather than a regular file does not exist but cannot be created or cannot be opened for any other reason

CET230 -- Razdan et al 27

BufferedWriter

Method Summary void

close() Close the stream

voidflush() Flush the stream

voidnewLine() Write a line separator

voidwrite(char[] cbuf int off int len) Write a portion of an array of characters

voidwrite(int c) Write a single character

voidwrite(String s int off int len) Write a portion of a String

CET230 -- Razdan et al 28

Write ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )BufferedWriter out = new BufferedWriter(

new FileWriter(outfile) )

String s = inreadLine()while( s = null )

outwrite((ssplit(ldquosrdquo))[0])outnewLine()s = inreadLine()

inclose()outclose()

CET230 -- Razdan et al 29

Java Interfaces

bull A Java interface is a set of related methods that a programmer may want to support in a single classndash Eg Cloneablendash Eg Comparablehttpjavasuncomj2se150docsapijavalangComparablehtml

CET230 -- Razdan et al 30

Iterator Pattern

bull Motivation ndash an aggregate object should give you a way to access its

elements without exposing its internal structure

ndash Use of the object may want to traverse the object in many different ways ndash donrsquot want to bloat the interface with may traversal methods even if you could anticipate all the methods needed

ndash May need to have more than one traversal pending on the aggregate at once

CET230 -- Razdan et al 31

Iterator Patternbull Key idea take responsibility for access and

traversal out of the object and put it into an iterator object

bull Iterator provides basic ldquonavigationrdquo methods eg ndash Firstndash Nextndash IsDonendash CurrentItem

CET230 -- Razdan et al 32

Map Interface

bull A map is a collection class in which keyvalue pairs may be added A pair can be retrieved or removed by specifying just its key

CET230 -- Razdan et al 33

TreeMap

bull Javarsquos TreeMapltK Vgt implements the map interface in an efficient way in which the keys are required to come from a class (such as String) that implements the Comparable interface

CET230 -- Razdan et al 34

Example

bull From package javautil

bull TreeMapltString Integergt frequencyData

bull String word

bull Integer count

CET230 -- Razdan et al 35

Operations

bull public V get(K key)

bull public V put(K key V value)

bull public boolean containsKey(K key)

bull public SetltKgt keySet()

bull public int size()

bull public void clear()

CET230 -- Razdan et al 36

Iteration

for (String word wordMapkeySet())

hellipprocess this key which is in variable wordhellip

  • Chapter 5 Generic Programming
  • Javarsquos Object type
  • Issues for ADT that hold objects
  • Widening Conversions
  • Narrowing Conversions
  • Wrapper Classes
  • Old vs New
  • Clones amp Deep Clones
  • Fix (kinda) previous
  • Really fix the shallow clone
  • List clone can use Node clone
  • Doubly Linked List
  • Inheritance
  • Other Lists
  • SkipList example from httpepaperpresscom
  • Abstract Classes
  • Abstract List
  • Implement clone in AbstractList
  • Reflection
  • Reflection cont
  • ldquoBionicrdquo Node
  • Revisiting the String class
  • Using Files for IO
  • FileReader constructor
  • Read Example
  • FileWriter constructor
  • BufferedWriter
  • Write Example
  • Java Interfaces
  • Iterator Pattern
  • Slide 31
  • Map Interface
  • TreeMap
  • Example
  • Operations
  • Iteration
Page 5: Chapter 5 Generic Programming Anshuman Razdan Div of Computing Studies razdan@asu.edu razdan/cst230

CET230 -- Razdan et al 5

Narrowing Conversions

bull If x and y are reference variables x=y is a narrowing conversion if x has a smaller ability to refer to things than y

bull Eg Object obj = new IntBag()

IntBag B

B = obj

By using a typecast Java will allow all narrowing conversions (a ClassCastException could be thrown if conversion is ldquoillegalrdquo)

CET230 -- Razdan et al 6

Wrapper Classes

bull A wrapper class is a class in which each object holds a primitive classndash Byte Short Integer Long Float Double

Character Boolean are wrapper classesndash Accessor methods xxxValue() where xxx is

primitive type

bull Note Java 15 provides ldquoauto-boxingrdquo which replaces need for Accessor methods

CET230 -- Razdan et al 7

Old vs Newbull Wrappers bull Boxing

ObjList L = new ObjList() must put primitive value 3 into an object (box it) in order to have an object to insert in the listLinsert( new Integer(3) )hellipInteger num = (Integer)LgetHead() now we must ldquoun-boxrdquo the primitive value int i = numintValue()

ObjList L = new ObjList() Java 15 will auto-boxLinsert( 3 )hellip Java 15 will auto-unboxint I = LgetHead()

bullSee httpjavasuncomj2se150docsguidelanguageautoboxinghtmlfor discussion on autoboxing

CET230 -- Razdan et al 8

Clones amp Deep Clonesbull Consider the following codeclass Node implements Cloneable private Object data private Node next

public Object clone() Node nodeClone try nodeClone = (Node) superclone() catch( CloneNotSupportedException e)

CET230 -- Razdan et al 9

Fix (kinda) previousbull The previous example is a ldquoshallowrdquo clone

bull Fix the code to make a deep(er) cloneclass Node implements Cloneable Object data Node next public Object clone() Node nodeClone try nodeClone = (Node) superclone() catch( CloneNotSupportedException e) nodeClonesetData( thisdata )

nodeClonesetNext( )

CET230 -- Razdan et al 10

Really fix the shallow clonebull We still have a problem with the previous code

Nodes hold Object so clones are referencing the same data

bull What wersquod like to do is

bull But this has a problemndash We donrsquot know the actual class that ldquodatardquo belongs to ndash

it might not be Cloneable

bull To fix this check if ldquodatardquo is instanceof Cloneable If so we can do the ldquodeeprdquo clone If not then wersquore stuck with referencing the same ldquodatardquo object

nodeClonesetData(thisgetData()clone())

CET230 -- Razdan et al 11

List clone can use Node clonebull If a Node is Cloneable then the List clone

is pretty easy (all the work is done by the Node)

bull Consider the following (for List clone)

listClonehead = (Node) thisheadclone()

bull Now we just need to set listClonetail How about the followinglistClonetail = (Node) thistailclone()

bull What can we do

CET230 -- Razdan et al 12

Doubly Linked Listbull A doubly linked list allows us to store

references to the next node as well as the previous node

3 2 7 11

headtail

CET230 -- Razdan et al 13

Inheritance

bull A Doubly Linked List ldquois-ardquo List So we should take advantage of the List wersquove already implementedndash DoubleNode extends Nodendash DoubleList extends List

CET230 -- Razdan et al 14

Other Lists

bull Other types of lists are usefulndash Ordered list (elements in list are stored in some

order) Eg numbers are in increasing order strings are in alphabetical order etc

ndash Circular List the ldquoendrdquo of the list refers back to the head

ndash Skip Lists

CET230 -- Razdan et al 15

SkipList example from httpepaperpresscom

CET230 -- Razdan et al 16

Abstract Classesbull A robust implementation for List is to have an

ldquoAbstractListrdquo class from which concrete Lists (Singly Linked Doubly Linked Ordered etc) can be derived

bull An abstract classndash Has at least one abstract method (a method whose

interface is defined but NO implementation is specified by the class)

ndash Cannot be instantiatedndash Can provide implementation for some methodsndash Can provide attributes common to all concrete

subclasses

CET230 -- Razdan et al 17

Abstract List

bull Attributesndash head tail length

bull Methodsndash Constructor getLength equals clone

bull Abstract Methodsndash Add remove clone

CET230 -- Razdan et al 18

Implement clone in AbstractList

bull What Irsquod really like is to implement the clone() in the AbstractList classndash All Lists contain Nodes We donrsquot want to

rewrite the same code for the clone method over and over again in the concrete List classes

ndash Problem what about a DoubleList that contains DoubleNode The AbstractList implementation will not do enoughbecause the Node clone does not do enough

ndash But I WANT it to do enough

CET230 -- Razdan et al 19

Reflectionbull What if we made the Node clone ldquosmarterrdquo

ndash if itrsquos just a Node then do a Node clonendash if itrsquos some other kind of Node then do that

clonendash But the Node doesnrsquot know all the other classes

that extend it

bull Reflection can be used to obtain information about a class its members or its methods

CET230 -- Razdan et al 20

Reflection cont

bull The Class class (see javalang) has methods that enable us to get information about the classndash eg getMethod(String name Class

[] parameterTypes) returns ldquoMethodrdquo

bull The Method class (see javalangreflect) has methods that enable us to get information about the Method and even CALL the methodndash Object invoke(Object obj Object[] args)

CET230 -- Razdan et al 21

ldquoBionicrdquo Nodebull We can modify the Node clone as follows

Node nodeClonetry nodeClone = (Node) superclone() catch( CloneNotSupportedException e ) throw new CloneNotSupportedException()if( thisdata instanceof Cloneable ) try Class c = thisdatagetClass() Method m = cgetMethod( clone null )

nodeClonedata = minvoke( thisdata null ) catch( Exception e ) nodeClonedata = thisdata else nodeClonedata = thisdataif( thisnext = null ) nodeClonenext = (Node) thisnextclone()else nodeClonenext = nullreturn( nodeClone )

CET230 -- Razdan et al 22

Revisiting the String classbull Some useful String methods

ndash charAt( int index)

ndash indexOf( char ch )

ndash indexOf( String str )

ndash split( String regex )

ndash startsWith( String prefix )

ndash substring( int beginIndex int endIndex )

ndash toLowerCase()

ndash toUpperCase()

Note StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code It is recommended that anyone seeking this functionality use the split method of String or the javautilregex package instead

CET230 -- Razdan et al 23

Using Files for IObull Using files for IO is similar to standard IObull For standard input you usually use

ndash InputStreamReaderndash BufferedReader

bull For standard output you usually usendash Systemoutprint or println

bull For file input you can usendash FileReaderndash BufferedReader

bull For file output you can usendash FileWriterndash BufferedWriter

CET230 -- Razdan et al 24

FileReader constructorFileReader

public FileReader(String fileName) throws FileNotFoundException

Creates a new FileReader given the name of the file to read from

Parameters fileName - the name of the file to read from

Throws FileNotFoundException - if the named file does not exist is a directory rather than a regular file or for some other reason cannot be opened for reading

CET230 -- Razdan et al 25

Read ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )

String s = inreadLine()int i = 1while( s = null )

Systemoutprintln(ldquoLine ldquo + i + ldquo ldquo + s )

i++s = inreadLine()

inclose()

CET230 -- Razdan et al 26

FileWriter constructor

FileWriter

public FileWriter(String fileName) throws IOException Constructs a FileWriter object given a file name

Parameters fileName - String The system-dependent filename

Throws IOException - if the named file exists but is a directory rather than a regular file does not exist but cannot be created or cannot be opened for any other reason

CET230 -- Razdan et al 27

BufferedWriter

Method Summary void

close() Close the stream

voidflush() Flush the stream

voidnewLine() Write a line separator

voidwrite(char[] cbuf int off int len) Write a portion of an array of characters

voidwrite(int c) Write a single character

voidwrite(String s int off int len) Write a portion of a String

CET230 -- Razdan et al 28

Write ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )BufferedWriter out = new BufferedWriter(

new FileWriter(outfile) )

String s = inreadLine()while( s = null )

outwrite((ssplit(ldquosrdquo))[0])outnewLine()s = inreadLine()

inclose()outclose()

CET230 -- Razdan et al 29

Java Interfaces

bull A Java interface is a set of related methods that a programmer may want to support in a single classndash Eg Cloneablendash Eg Comparablehttpjavasuncomj2se150docsapijavalangComparablehtml

CET230 -- Razdan et al 30

Iterator Pattern

bull Motivation ndash an aggregate object should give you a way to access its

elements without exposing its internal structure

ndash Use of the object may want to traverse the object in many different ways ndash donrsquot want to bloat the interface with may traversal methods even if you could anticipate all the methods needed

ndash May need to have more than one traversal pending on the aggregate at once

CET230 -- Razdan et al 31

Iterator Patternbull Key idea take responsibility for access and

traversal out of the object and put it into an iterator object

bull Iterator provides basic ldquonavigationrdquo methods eg ndash Firstndash Nextndash IsDonendash CurrentItem

CET230 -- Razdan et al 32

Map Interface

bull A map is a collection class in which keyvalue pairs may be added A pair can be retrieved or removed by specifying just its key

CET230 -- Razdan et al 33

TreeMap

bull Javarsquos TreeMapltK Vgt implements the map interface in an efficient way in which the keys are required to come from a class (such as String) that implements the Comparable interface

CET230 -- Razdan et al 34

Example

bull From package javautil

bull TreeMapltString Integergt frequencyData

bull String word

bull Integer count

CET230 -- Razdan et al 35

Operations

bull public V get(K key)

bull public V put(K key V value)

bull public boolean containsKey(K key)

bull public SetltKgt keySet()

bull public int size()

bull public void clear()

CET230 -- Razdan et al 36

Iteration

for (String word wordMapkeySet())

hellipprocess this key which is in variable wordhellip

  • Chapter 5 Generic Programming
  • Javarsquos Object type
  • Issues for ADT that hold objects
  • Widening Conversions
  • Narrowing Conversions
  • Wrapper Classes
  • Old vs New
  • Clones amp Deep Clones
  • Fix (kinda) previous
  • Really fix the shallow clone
  • List clone can use Node clone
  • Doubly Linked List
  • Inheritance
  • Other Lists
  • SkipList example from httpepaperpresscom
  • Abstract Classes
  • Abstract List
  • Implement clone in AbstractList
  • Reflection
  • Reflection cont
  • ldquoBionicrdquo Node
  • Revisiting the String class
  • Using Files for IO
  • FileReader constructor
  • Read Example
  • FileWriter constructor
  • BufferedWriter
  • Write Example
  • Java Interfaces
  • Iterator Pattern
  • Slide 31
  • Map Interface
  • TreeMap
  • Example
  • Operations
  • Iteration
Page 6: Chapter 5 Generic Programming Anshuman Razdan Div of Computing Studies razdan@asu.edu razdan/cst230

CET230 -- Razdan et al 6

Wrapper Classes

bull A wrapper class is a class in which each object holds a primitive classndash Byte Short Integer Long Float Double

Character Boolean are wrapper classesndash Accessor methods xxxValue() where xxx is

primitive type

bull Note Java 15 provides ldquoauto-boxingrdquo which replaces need for Accessor methods

CET230 -- Razdan et al 7

Old vs Newbull Wrappers bull Boxing

ObjList L = new ObjList() must put primitive value 3 into an object (box it) in order to have an object to insert in the listLinsert( new Integer(3) )hellipInteger num = (Integer)LgetHead() now we must ldquoun-boxrdquo the primitive value int i = numintValue()

ObjList L = new ObjList() Java 15 will auto-boxLinsert( 3 )hellip Java 15 will auto-unboxint I = LgetHead()

bullSee httpjavasuncomj2se150docsguidelanguageautoboxinghtmlfor discussion on autoboxing

CET230 -- Razdan et al 8

Clones amp Deep Clonesbull Consider the following codeclass Node implements Cloneable private Object data private Node next

public Object clone() Node nodeClone try nodeClone = (Node) superclone() catch( CloneNotSupportedException e)

CET230 -- Razdan et al 9

Fix (kinda) previousbull The previous example is a ldquoshallowrdquo clone

bull Fix the code to make a deep(er) cloneclass Node implements Cloneable Object data Node next public Object clone() Node nodeClone try nodeClone = (Node) superclone() catch( CloneNotSupportedException e) nodeClonesetData( thisdata )

nodeClonesetNext( )

CET230 -- Razdan et al 10

Really fix the shallow clonebull We still have a problem with the previous code

Nodes hold Object so clones are referencing the same data

bull What wersquod like to do is

bull But this has a problemndash We donrsquot know the actual class that ldquodatardquo belongs to ndash

it might not be Cloneable

bull To fix this check if ldquodatardquo is instanceof Cloneable If so we can do the ldquodeeprdquo clone If not then wersquore stuck with referencing the same ldquodatardquo object

nodeClonesetData(thisgetData()clone())

CET230 -- Razdan et al 11

List clone can use Node clonebull If a Node is Cloneable then the List clone

is pretty easy (all the work is done by the Node)

bull Consider the following (for List clone)

listClonehead = (Node) thisheadclone()

bull Now we just need to set listClonetail How about the followinglistClonetail = (Node) thistailclone()

bull What can we do

CET230 -- Razdan et al 12

Doubly Linked Listbull A doubly linked list allows us to store

references to the next node as well as the previous node

3 2 7 11

headtail

CET230 -- Razdan et al 13

Inheritance

bull A Doubly Linked List ldquois-ardquo List So we should take advantage of the List wersquove already implementedndash DoubleNode extends Nodendash DoubleList extends List

CET230 -- Razdan et al 14

Other Lists

bull Other types of lists are usefulndash Ordered list (elements in list are stored in some

order) Eg numbers are in increasing order strings are in alphabetical order etc

ndash Circular List the ldquoendrdquo of the list refers back to the head

ndash Skip Lists

CET230 -- Razdan et al 15

SkipList example from httpepaperpresscom

CET230 -- Razdan et al 16

Abstract Classesbull A robust implementation for List is to have an

ldquoAbstractListrdquo class from which concrete Lists (Singly Linked Doubly Linked Ordered etc) can be derived

bull An abstract classndash Has at least one abstract method (a method whose

interface is defined but NO implementation is specified by the class)

ndash Cannot be instantiatedndash Can provide implementation for some methodsndash Can provide attributes common to all concrete

subclasses

CET230 -- Razdan et al 17

Abstract List

bull Attributesndash head tail length

bull Methodsndash Constructor getLength equals clone

bull Abstract Methodsndash Add remove clone

CET230 -- Razdan et al 18

Implement clone in AbstractList

bull What Irsquod really like is to implement the clone() in the AbstractList classndash All Lists contain Nodes We donrsquot want to

rewrite the same code for the clone method over and over again in the concrete List classes

ndash Problem what about a DoubleList that contains DoubleNode The AbstractList implementation will not do enoughbecause the Node clone does not do enough

ndash But I WANT it to do enough

CET230 -- Razdan et al 19

Reflectionbull What if we made the Node clone ldquosmarterrdquo

ndash if itrsquos just a Node then do a Node clonendash if itrsquos some other kind of Node then do that

clonendash But the Node doesnrsquot know all the other classes

that extend it

bull Reflection can be used to obtain information about a class its members or its methods

CET230 -- Razdan et al 20

Reflection cont

bull The Class class (see javalang) has methods that enable us to get information about the classndash eg getMethod(String name Class

[] parameterTypes) returns ldquoMethodrdquo

bull The Method class (see javalangreflect) has methods that enable us to get information about the Method and even CALL the methodndash Object invoke(Object obj Object[] args)

CET230 -- Razdan et al 21

ldquoBionicrdquo Nodebull We can modify the Node clone as follows

Node nodeClonetry nodeClone = (Node) superclone() catch( CloneNotSupportedException e ) throw new CloneNotSupportedException()if( thisdata instanceof Cloneable ) try Class c = thisdatagetClass() Method m = cgetMethod( clone null )

nodeClonedata = minvoke( thisdata null ) catch( Exception e ) nodeClonedata = thisdata else nodeClonedata = thisdataif( thisnext = null ) nodeClonenext = (Node) thisnextclone()else nodeClonenext = nullreturn( nodeClone )

CET230 -- Razdan et al 22

Revisiting the String classbull Some useful String methods

ndash charAt( int index)

ndash indexOf( char ch )

ndash indexOf( String str )

ndash split( String regex )

ndash startsWith( String prefix )

ndash substring( int beginIndex int endIndex )

ndash toLowerCase()

ndash toUpperCase()

Note StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code It is recommended that anyone seeking this functionality use the split method of String or the javautilregex package instead

CET230 -- Razdan et al 23

Using Files for IObull Using files for IO is similar to standard IObull For standard input you usually use

ndash InputStreamReaderndash BufferedReader

bull For standard output you usually usendash Systemoutprint or println

bull For file input you can usendash FileReaderndash BufferedReader

bull For file output you can usendash FileWriterndash BufferedWriter

CET230 -- Razdan et al 24

FileReader constructorFileReader

public FileReader(String fileName) throws FileNotFoundException

Creates a new FileReader given the name of the file to read from

Parameters fileName - the name of the file to read from

Throws FileNotFoundException - if the named file does not exist is a directory rather than a regular file or for some other reason cannot be opened for reading

CET230 -- Razdan et al 25

Read ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )

String s = inreadLine()int i = 1while( s = null )

Systemoutprintln(ldquoLine ldquo + i + ldquo ldquo + s )

i++s = inreadLine()

inclose()

CET230 -- Razdan et al 26

FileWriter constructor

FileWriter

public FileWriter(String fileName) throws IOException Constructs a FileWriter object given a file name

Parameters fileName - String The system-dependent filename

Throws IOException - if the named file exists but is a directory rather than a regular file does not exist but cannot be created or cannot be opened for any other reason

CET230 -- Razdan et al 27

BufferedWriter

Method Summary void

close() Close the stream

voidflush() Flush the stream

voidnewLine() Write a line separator

voidwrite(char[] cbuf int off int len) Write a portion of an array of characters

voidwrite(int c) Write a single character

voidwrite(String s int off int len) Write a portion of a String

CET230 -- Razdan et al 28

Write ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )BufferedWriter out = new BufferedWriter(

new FileWriter(outfile) )

String s = inreadLine()while( s = null )

outwrite((ssplit(ldquosrdquo))[0])outnewLine()s = inreadLine()

inclose()outclose()

CET230 -- Razdan et al 29

Java Interfaces

bull A Java interface is a set of related methods that a programmer may want to support in a single classndash Eg Cloneablendash Eg Comparablehttpjavasuncomj2se150docsapijavalangComparablehtml

CET230 -- Razdan et al 30

Iterator Pattern

bull Motivation ndash an aggregate object should give you a way to access its

elements without exposing its internal structure

ndash Use of the object may want to traverse the object in many different ways ndash donrsquot want to bloat the interface with may traversal methods even if you could anticipate all the methods needed

ndash May need to have more than one traversal pending on the aggregate at once

CET230 -- Razdan et al 31

Iterator Patternbull Key idea take responsibility for access and

traversal out of the object and put it into an iterator object

bull Iterator provides basic ldquonavigationrdquo methods eg ndash Firstndash Nextndash IsDonendash CurrentItem

CET230 -- Razdan et al 32

Map Interface

bull A map is a collection class in which keyvalue pairs may be added A pair can be retrieved or removed by specifying just its key

CET230 -- Razdan et al 33

TreeMap

bull Javarsquos TreeMapltK Vgt implements the map interface in an efficient way in which the keys are required to come from a class (such as String) that implements the Comparable interface

CET230 -- Razdan et al 34

Example

bull From package javautil

bull TreeMapltString Integergt frequencyData

bull String word

bull Integer count

CET230 -- Razdan et al 35

Operations

bull public V get(K key)

bull public V put(K key V value)

bull public boolean containsKey(K key)

bull public SetltKgt keySet()

bull public int size()

bull public void clear()

CET230 -- Razdan et al 36

Iteration

for (String word wordMapkeySet())

hellipprocess this key which is in variable wordhellip

  • Chapter 5 Generic Programming
  • Javarsquos Object type
  • Issues for ADT that hold objects
  • Widening Conversions
  • Narrowing Conversions
  • Wrapper Classes
  • Old vs New
  • Clones amp Deep Clones
  • Fix (kinda) previous
  • Really fix the shallow clone
  • List clone can use Node clone
  • Doubly Linked List
  • Inheritance
  • Other Lists
  • SkipList example from httpepaperpresscom
  • Abstract Classes
  • Abstract List
  • Implement clone in AbstractList
  • Reflection
  • Reflection cont
  • ldquoBionicrdquo Node
  • Revisiting the String class
  • Using Files for IO
  • FileReader constructor
  • Read Example
  • FileWriter constructor
  • BufferedWriter
  • Write Example
  • Java Interfaces
  • Iterator Pattern
  • Slide 31
  • Map Interface
  • TreeMap
  • Example
  • Operations
  • Iteration
Page 7: Chapter 5 Generic Programming Anshuman Razdan Div of Computing Studies razdan@asu.edu razdan/cst230

CET230 -- Razdan et al 7

Old vs Newbull Wrappers bull Boxing

ObjList L = new ObjList() must put primitive value 3 into an object (box it) in order to have an object to insert in the listLinsert( new Integer(3) )hellipInteger num = (Integer)LgetHead() now we must ldquoun-boxrdquo the primitive value int i = numintValue()

ObjList L = new ObjList() Java 15 will auto-boxLinsert( 3 )hellip Java 15 will auto-unboxint I = LgetHead()

bullSee httpjavasuncomj2se150docsguidelanguageautoboxinghtmlfor discussion on autoboxing

CET230 -- Razdan et al 8

Clones amp Deep Clonesbull Consider the following codeclass Node implements Cloneable private Object data private Node next

public Object clone() Node nodeClone try nodeClone = (Node) superclone() catch( CloneNotSupportedException e)

CET230 -- Razdan et al 9

Fix (kinda) previousbull The previous example is a ldquoshallowrdquo clone

bull Fix the code to make a deep(er) cloneclass Node implements Cloneable Object data Node next public Object clone() Node nodeClone try nodeClone = (Node) superclone() catch( CloneNotSupportedException e) nodeClonesetData( thisdata )

nodeClonesetNext( )

CET230 -- Razdan et al 10

Really fix the shallow clonebull We still have a problem with the previous code

Nodes hold Object so clones are referencing the same data

bull What wersquod like to do is

bull But this has a problemndash We donrsquot know the actual class that ldquodatardquo belongs to ndash

it might not be Cloneable

bull To fix this check if ldquodatardquo is instanceof Cloneable If so we can do the ldquodeeprdquo clone If not then wersquore stuck with referencing the same ldquodatardquo object

nodeClonesetData(thisgetData()clone())

CET230 -- Razdan et al 11

List clone can use Node clonebull If a Node is Cloneable then the List clone

is pretty easy (all the work is done by the Node)

bull Consider the following (for List clone)

listClonehead = (Node) thisheadclone()

bull Now we just need to set listClonetail How about the followinglistClonetail = (Node) thistailclone()

bull What can we do

CET230 -- Razdan et al 12

Doubly Linked Listbull A doubly linked list allows us to store

references to the next node as well as the previous node

3 2 7 11

headtail

CET230 -- Razdan et al 13

Inheritance

bull A Doubly Linked List ldquois-ardquo List So we should take advantage of the List wersquove already implementedndash DoubleNode extends Nodendash DoubleList extends List

CET230 -- Razdan et al 14

Other Lists

bull Other types of lists are usefulndash Ordered list (elements in list are stored in some

order) Eg numbers are in increasing order strings are in alphabetical order etc

ndash Circular List the ldquoendrdquo of the list refers back to the head

ndash Skip Lists

CET230 -- Razdan et al 15

SkipList example from httpepaperpresscom

CET230 -- Razdan et al 16

Abstract Classesbull A robust implementation for List is to have an

ldquoAbstractListrdquo class from which concrete Lists (Singly Linked Doubly Linked Ordered etc) can be derived

bull An abstract classndash Has at least one abstract method (a method whose

interface is defined but NO implementation is specified by the class)

ndash Cannot be instantiatedndash Can provide implementation for some methodsndash Can provide attributes common to all concrete

subclasses

CET230 -- Razdan et al 17

Abstract List

bull Attributesndash head tail length

bull Methodsndash Constructor getLength equals clone

bull Abstract Methodsndash Add remove clone

CET230 -- Razdan et al 18

Implement clone in AbstractList

bull What Irsquod really like is to implement the clone() in the AbstractList classndash All Lists contain Nodes We donrsquot want to

rewrite the same code for the clone method over and over again in the concrete List classes

ndash Problem what about a DoubleList that contains DoubleNode The AbstractList implementation will not do enoughbecause the Node clone does not do enough

ndash But I WANT it to do enough

CET230 -- Razdan et al 19

Reflectionbull What if we made the Node clone ldquosmarterrdquo

ndash if itrsquos just a Node then do a Node clonendash if itrsquos some other kind of Node then do that

clonendash But the Node doesnrsquot know all the other classes

that extend it

bull Reflection can be used to obtain information about a class its members or its methods

CET230 -- Razdan et al 20

Reflection cont

bull The Class class (see javalang) has methods that enable us to get information about the classndash eg getMethod(String name Class

[] parameterTypes) returns ldquoMethodrdquo

bull The Method class (see javalangreflect) has methods that enable us to get information about the Method and even CALL the methodndash Object invoke(Object obj Object[] args)

CET230 -- Razdan et al 21

ldquoBionicrdquo Nodebull We can modify the Node clone as follows

Node nodeClonetry nodeClone = (Node) superclone() catch( CloneNotSupportedException e ) throw new CloneNotSupportedException()if( thisdata instanceof Cloneable ) try Class c = thisdatagetClass() Method m = cgetMethod( clone null )

nodeClonedata = minvoke( thisdata null ) catch( Exception e ) nodeClonedata = thisdata else nodeClonedata = thisdataif( thisnext = null ) nodeClonenext = (Node) thisnextclone()else nodeClonenext = nullreturn( nodeClone )

CET230 -- Razdan et al 22

Revisiting the String classbull Some useful String methods

ndash charAt( int index)

ndash indexOf( char ch )

ndash indexOf( String str )

ndash split( String regex )

ndash startsWith( String prefix )

ndash substring( int beginIndex int endIndex )

ndash toLowerCase()

ndash toUpperCase()

Note StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code It is recommended that anyone seeking this functionality use the split method of String or the javautilregex package instead

CET230 -- Razdan et al 23

Using Files for IObull Using files for IO is similar to standard IObull For standard input you usually use

ndash InputStreamReaderndash BufferedReader

bull For standard output you usually usendash Systemoutprint or println

bull For file input you can usendash FileReaderndash BufferedReader

bull For file output you can usendash FileWriterndash BufferedWriter

CET230 -- Razdan et al 24

FileReader constructorFileReader

public FileReader(String fileName) throws FileNotFoundException

Creates a new FileReader given the name of the file to read from

Parameters fileName - the name of the file to read from

Throws FileNotFoundException - if the named file does not exist is a directory rather than a regular file or for some other reason cannot be opened for reading

CET230 -- Razdan et al 25

Read ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )

String s = inreadLine()int i = 1while( s = null )

Systemoutprintln(ldquoLine ldquo + i + ldquo ldquo + s )

i++s = inreadLine()

inclose()

CET230 -- Razdan et al 26

FileWriter constructor

FileWriter

public FileWriter(String fileName) throws IOException Constructs a FileWriter object given a file name

Parameters fileName - String The system-dependent filename

Throws IOException - if the named file exists but is a directory rather than a regular file does not exist but cannot be created or cannot be opened for any other reason

CET230 -- Razdan et al 27

BufferedWriter

Method Summary void

close() Close the stream

voidflush() Flush the stream

voidnewLine() Write a line separator

voidwrite(char[] cbuf int off int len) Write a portion of an array of characters

voidwrite(int c) Write a single character

voidwrite(String s int off int len) Write a portion of a String

CET230 -- Razdan et al 28

Write ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )BufferedWriter out = new BufferedWriter(

new FileWriter(outfile) )

String s = inreadLine()while( s = null )

outwrite((ssplit(ldquosrdquo))[0])outnewLine()s = inreadLine()

inclose()outclose()

CET230 -- Razdan et al 29

Java Interfaces

bull A Java interface is a set of related methods that a programmer may want to support in a single classndash Eg Cloneablendash Eg Comparablehttpjavasuncomj2se150docsapijavalangComparablehtml

CET230 -- Razdan et al 30

Iterator Pattern

bull Motivation ndash an aggregate object should give you a way to access its

elements without exposing its internal structure

ndash Use of the object may want to traverse the object in many different ways ndash donrsquot want to bloat the interface with may traversal methods even if you could anticipate all the methods needed

ndash May need to have more than one traversal pending on the aggregate at once

CET230 -- Razdan et al 31

Iterator Patternbull Key idea take responsibility for access and

traversal out of the object and put it into an iterator object

bull Iterator provides basic ldquonavigationrdquo methods eg ndash Firstndash Nextndash IsDonendash CurrentItem

CET230 -- Razdan et al 32

Map Interface

bull A map is a collection class in which keyvalue pairs may be added A pair can be retrieved or removed by specifying just its key

CET230 -- Razdan et al 33

TreeMap

bull Javarsquos TreeMapltK Vgt implements the map interface in an efficient way in which the keys are required to come from a class (such as String) that implements the Comparable interface

CET230 -- Razdan et al 34

Example

bull From package javautil

bull TreeMapltString Integergt frequencyData

bull String word

bull Integer count

CET230 -- Razdan et al 35

Operations

bull public V get(K key)

bull public V put(K key V value)

bull public boolean containsKey(K key)

bull public SetltKgt keySet()

bull public int size()

bull public void clear()

CET230 -- Razdan et al 36

Iteration

for (String word wordMapkeySet())

hellipprocess this key which is in variable wordhellip

  • Chapter 5 Generic Programming
  • Javarsquos Object type
  • Issues for ADT that hold objects
  • Widening Conversions
  • Narrowing Conversions
  • Wrapper Classes
  • Old vs New
  • Clones amp Deep Clones
  • Fix (kinda) previous
  • Really fix the shallow clone
  • List clone can use Node clone
  • Doubly Linked List
  • Inheritance
  • Other Lists
  • SkipList example from httpepaperpresscom
  • Abstract Classes
  • Abstract List
  • Implement clone in AbstractList
  • Reflection
  • Reflection cont
  • ldquoBionicrdquo Node
  • Revisiting the String class
  • Using Files for IO
  • FileReader constructor
  • Read Example
  • FileWriter constructor
  • BufferedWriter
  • Write Example
  • Java Interfaces
  • Iterator Pattern
  • Slide 31
  • Map Interface
  • TreeMap
  • Example
  • Operations
  • Iteration
Page 8: Chapter 5 Generic Programming Anshuman Razdan Div of Computing Studies razdan@asu.edu razdan/cst230

CET230 -- Razdan et al 8

Clones amp Deep Clonesbull Consider the following codeclass Node implements Cloneable private Object data private Node next

public Object clone() Node nodeClone try nodeClone = (Node) superclone() catch( CloneNotSupportedException e)

CET230 -- Razdan et al 9

Fix (kinda) previousbull The previous example is a ldquoshallowrdquo clone

bull Fix the code to make a deep(er) cloneclass Node implements Cloneable Object data Node next public Object clone() Node nodeClone try nodeClone = (Node) superclone() catch( CloneNotSupportedException e) nodeClonesetData( thisdata )

nodeClonesetNext( )

CET230 -- Razdan et al 10

Really fix the shallow clonebull We still have a problem with the previous code

Nodes hold Object so clones are referencing the same data

bull What wersquod like to do is

bull But this has a problemndash We donrsquot know the actual class that ldquodatardquo belongs to ndash

it might not be Cloneable

bull To fix this check if ldquodatardquo is instanceof Cloneable If so we can do the ldquodeeprdquo clone If not then wersquore stuck with referencing the same ldquodatardquo object

nodeClonesetData(thisgetData()clone())

CET230 -- Razdan et al 11

List clone can use Node clonebull If a Node is Cloneable then the List clone

is pretty easy (all the work is done by the Node)

bull Consider the following (for List clone)

listClonehead = (Node) thisheadclone()

bull Now we just need to set listClonetail How about the followinglistClonetail = (Node) thistailclone()

bull What can we do

CET230 -- Razdan et al 12

Doubly Linked Listbull A doubly linked list allows us to store

references to the next node as well as the previous node

3 2 7 11

headtail

CET230 -- Razdan et al 13

Inheritance

bull A Doubly Linked List ldquois-ardquo List So we should take advantage of the List wersquove already implementedndash DoubleNode extends Nodendash DoubleList extends List

CET230 -- Razdan et al 14

Other Lists

bull Other types of lists are usefulndash Ordered list (elements in list are stored in some

order) Eg numbers are in increasing order strings are in alphabetical order etc

ndash Circular List the ldquoendrdquo of the list refers back to the head

ndash Skip Lists

CET230 -- Razdan et al 15

SkipList example from httpepaperpresscom

CET230 -- Razdan et al 16

Abstract Classesbull A robust implementation for List is to have an

ldquoAbstractListrdquo class from which concrete Lists (Singly Linked Doubly Linked Ordered etc) can be derived

bull An abstract classndash Has at least one abstract method (a method whose

interface is defined but NO implementation is specified by the class)

ndash Cannot be instantiatedndash Can provide implementation for some methodsndash Can provide attributes common to all concrete

subclasses

CET230 -- Razdan et al 17

Abstract List

bull Attributesndash head tail length

bull Methodsndash Constructor getLength equals clone

bull Abstract Methodsndash Add remove clone

CET230 -- Razdan et al 18

Implement clone in AbstractList

bull What Irsquod really like is to implement the clone() in the AbstractList classndash All Lists contain Nodes We donrsquot want to

rewrite the same code for the clone method over and over again in the concrete List classes

ndash Problem what about a DoubleList that contains DoubleNode The AbstractList implementation will not do enoughbecause the Node clone does not do enough

ndash But I WANT it to do enough

CET230 -- Razdan et al 19

Reflectionbull What if we made the Node clone ldquosmarterrdquo

ndash if itrsquos just a Node then do a Node clonendash if itrsquos some other kind of Node then do that

clonendash But the Node doesnrsquot know all the other classes

that extend it

bull Reflection can be used to obtain information about a class its members or its methods

CET230 -- Razdan et al 20

Reflection cont

bull The Class class (see javalang) has methods that enable us to get information about the classndash eg getMethod(String name Class

[] parameterTypes) returns ldquoMethodrdquo

bull The Method class (see javalangreflect) has methods that enable us to get information about the Method and even CALL the methodndash Object invoke(Object obj Object[] args)

CET230 -- Razdan et al 21

ldquoBionicrdquo Nodebull We can modify the Node clone as follows

Node nodeClonetry nodeClone = (Node) superclone() catch( CloneNotSupportedException e ) throw new CloneNotSupportedException()if( thisdata instanceof Cloneable ) try Class c = thisdatagetClass() Method m = cgetMethod( clone null )

nodeClonedata = minvoke( thisdata null ) catch( Exception e ) nodeClonedata = thisdata else nodeClonedata = thisdataif( thisnext = null ) nodeClonenext = (Node) thisnextclone()else nodeClonenext = nullreturn( nodeClone )

CET230 -- Razdan et al 22

Revisiting the String classbull Some useful String methods

ndash charAt( int index)

ndash indexOf( char ch )

ndash indexOf( String str )

ndash split( String regex )

ndash startsWith( String prefix )

ndash substring( int beginIndex int endIndex )

ndash toLowerCase()

ndash toUpperCase()

Note StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code It is recommended that anyone seeking this functionality use the split method of String or the javautilregex package instead

CET230 -- Razdan et al 23

Using Files for IObull Using files for IO is similar to standard IObull For standard input you usually use

ndash InputStreamReaderndash BufferedReader

bull For standard output you usually usendash Systemoutprint or println

bull For file input you can usendash FileReaderndash BufferedReader

bull For file output you can usendash FileWriterndash BufferedWriter

CET230 -- Razdan et al 24

FileReader constructorFileReader

public FileReader(String fileName) throws FileNotFoundException

Creates a new FileReader given the name of the file to read from

Parameters fileName - the name of the file to read from

Throws FileNotFoundException - if the named file does not exist is a directory rather than a regular file or for some other reason cannot be opened for reading

CET230 -- Razdan et al 25

Read ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )

String s = inreadLine()int i = 1while( s = null )

Systemoutprintln(ldquoLine ldquo + i + ldquo ldquo + s )

i++s = inreadLine()

inclose()

CET230 -- Razdan et al 26

FileWriter constructor

FileWriter

public FileWriter(String fileName) throws IOException Constructs a FileWriter object given a file name

Parameters fileName - String The system-dependent filename

Throws IOException - if the named file exists but is a directory rather than a regular file does not exist but cannot be created or cannot be opened for any other reason

CET230 -- Razdan et al 27

BufferedWriter

Method Summary void

close() Close the stream

voidflush() Flush the stream

voidnewLine() Write a line separator

voidwrite(char[] cbuf int off int len) Write a portion of an array of characters

voidwrite(int c) Write a single character

voidwrite(String s int off int len) Write a portion of a String

CET230 -- Razdan et al 28

Write ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )BufferedWriter out = new BufferedWriter(

new FileWriter(outfile) )

String s = inreadLine()while( s = null )

outwrite((ssplit(ldquosrdquo))[0])outnewLine()s = inreadLine()

inclose()outclose()

CET230 -- Razdan et al 29

Java Interfaces

bull A Java interface is a set of related methods that a programmer may want to support in a single classndash Eg Cloneablendash Eg Comparablehttpjavasuncomj2se150docsapijavalangComparablehtml

CET230 -- Razdan et al 30

Iterator Pattern

bull Motivation ndash an aggregate object should give you a way to access its

elements without exposing its internal structure

ndash Use of the object may want to traverse the object in many different ways ndash donrsquot want to bloat the interface with may traversal methods even if you could anticipate all the methods needed

ndash May need to have more than one traversal pending on the aggregate at once

CET230 -- Razdan et al 31

Iterator Patternbull Key idea take responsibility for access and

traversal out of the object and put it into an iterator object

bull Iterator provides basic ldquonavigationrdquo methods eg ndash Firstndash Nextndash IsDonendash CurrentItem

CET230 -- Razdan et al 32

Map Interface

bull A map is a collection class in which keyvalue pairs may be added A pair can be retrieved or removed by specifying just its key

CET230 -- Razdan et al 33

TreeMap

bull Javarsquos TreeMapltK Vgt implements the map interface in an efficient way in which the keys are required to come from a class (such as String) that implements the Comparable interface

CET230 -- Razdan et al 34

Example

bull From package javautil

bull TreeMapltString Integergt frequencyData

bull String word

bull Integer count

CET230 -- Razdan et al 35

Operations

bull public V get(K key)

bull public V put(K key V value)

bull public boolean containsKey(K key)

bull public SetltKgt keySet()

bull public int size()

bull public void clear()

CET230 -- Razdan et al 36

Iteration

for (String word wordMapkeySet())

hellipprocess this key which is in variable wordhellip

  • Chapter 5 Generic Programming
  • Javarsquos Object type
  • Issues for ADT that hold objects
  • Widening Conversions
  • Narrowing Conversions
  • Wrapper Classes
  • Old vs New
  • Clones amp Deep Clones
  • Fix (kinda) previous
  • Really fix the shallow clone
  • List clone can use Node clone
  • Doubly Linked List
  • Inheritance
  • Other Lists
  • SkipList example from httpepaperpresscom
  • Abstract Classes
  • Abstract List
  • Implement clone in AbstractList
  • Reflection
  • Reflection cont
  • ldquoBionicrdquo Node
  • Revisiting the String class
  • Using Files for IO
  • FileReader constructor
  • Read Example
  • FileWriter constructor
  • BufferedWriter
  • Write Example
  • Java Interfaces
  • Iterator Pattern
  • Slide 31
  • Map Interface
  • TreeMap
  • Example
  • Operations
  • Iteration
Page 9: Chapter 5 Generic Programming Anshuman Razdan Div of Computing Studies razdan@asu.edu razdan/cst230

CET230 -- Razdan et al 9

Fix (kinda) previousbull The previous example is a ldquoshallowrdquo clone

bull Fix the code to make a deep(er) cloneclass Node implements Cloneable Object data Node next public Object clone() Node nodeClone try nodeClone = (Node) superclone() catch( CloneNotSupportedException e) nodeClonesetData( thisdata )

nodeClonesetNext( )

CET230 -- Razdan et al 10

Really fix the shallow clonebull We still have a problem with the previous code

Nodes hold Object so clones are referencing the same data

bull What wersquod like to do is

bull But this has a problemndash We donrsquot know the actual class that ldquodatardquo belongs to ndash

it might not be Cloneable

bull To fix this check if ldquodatardquo is instanceof Cloneable If so we can do the ldquodeeprdquo clone If not then wersquore stuck with referencing the same ldquodatardquo object

nodeClonesetData(thisgetData()clone())

CET230 -- Razdan et al 11

List clone can use Node clonebull If a Node is Cloneable then the List clone

is pretty easy (all the work is done by the Node)

bull Consider the following (for List clone)

listClonehead = (Node) thisheadclone()

bull Now we just need to set listClonetail How about the followinglistClonetail = (Node) thistailclone()

bull What can we do

CET230 -- Razdan et al 12

Doubly Linked Listbull A doubly linked list allows us to store

references to the next node as well as the previous node

3 2 7 11

headtail

CET230 -- Razdan et al 13

Inheritance

bull A Doubly Linked List ldquois-ardquo List So we should take advantage of the List wersquove already implementedndash DoubleNode extends Nodendash DoubleList extends List

CET230 -- Razdan et al 14

Other Lists

bull Other types of lists are usefulndash Ordered list (elements in list are stored in some

order) Eg numbers are in increasing order strings are in alphabetical order etc

ndash Circular List the ldquoendrdquo of the list refers back to the head

ndash Skip Lists

CET230 -- Razdan et al 15

SkipList example from httpepaperpresscom

CET230 -- Razdan et al 16

Abstract Classesbull A robust implementation for List is to have an

ldquoAbstractListrdquo class from which concrete Lists (Singly Linked Doubly Linked Ordered etc) can be derived

bull An abstract classndash Has at least one abstract method (a method whose

interface is defined but NO implementation is specified by the class)

ndash Cannot be instantiatedndash Can provide implementation for some methodsndash Can provide attributes common to all concrete

subclasses

CET230 -- Razdan et al 17

Abstract List

bull Attributesndash head tail length

bull Methodsndash Constructor getLength equals clone

bull Abstract Methodsndash Add remove clone

CET230 -- Razdan et al 18

Implement clone in AbstractList

bull What Irsquod really like is to implement the clone() in the AbstractList classndash All Lists contain Nodes We donrsquot want to

rewrite the same code for the clone method over and over again in the concrete List classes

ndash Problem what about a DoubleList that contains DoubleNode The AbstractList implementation will not do enoughbecause the Node clone does not do enough

ndash But I WANT it to do enough

CET230 -- Razdan et al 19

Reflectionbull What if we made the Node clone ldquosmarterrdquo

ndash if itrsquos just a Node then do a Node clonendash if itrsquos some other kind of Node then do that

clonendash But the Node doesnrsquot know all the other classes

that extend it

bull Reflection can be used to obtain information about a class its members or its methods

CET230 -- Razdan et al 20

Reflection cont

bull The Class class (see javalang) has methods that enable us to get information about the classndash eg getMethod(String name Class

[] parameterTypes) returns ldquoMethodrdquo

bull The Method class (see javalangreflect) has methods that enable us to get information about the Method and even CALL the methodndash Object invoke(Object obj Object[] args)

CET230 -- Razdan et al 21

ldquoBionicrdquo Nodebull We can modify the Node clone as follows

Node nodeClonetry nodeClone = (Node) superclone() catch( CloneNotSupportedException e ) throw new CloneNotSupportedException()if( thisdata instanceof Cloneable ) try Class c = thisdatagetClass() Method m = cgetMethod( clone null )

nodeClonedata = minvoke( thisdata null ) catch( Exception e ) nodeClonedata = thisdata else nodeClonedata = thisdataif( thisnext = null ) nodeClonenext = (Node) thisnextclone()else nodeClonenext = nullreturn( nodeClone )

CET230 -- Razdan et al 22

Revisiting the String classbull Some useful String methods

ndash charAt( int index)

ndash indexOf( char ch )

ndash indexOf( String str )

ndash split( String regex )

ndash startsWith( String prefix )

ndash substring( int beginIndex int endIndex )

ndash toLowerCase()

ndash toUpperCase()

Note StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code It is recommended that anyone seeking this functionality use the split method of String or the javautilregex package instead

CET230 -- Razdan et al 23

Using Files for IObull Using files for IO is similar to standard IObull For standard input you usually use

ndash InputStreamReaderndash BufferedReader

bull For standard output you usually usendash Systemoutprint or println

bull For file input you can usendash FileReaderndash BufferedReader

bull For file output you can usendash FileWriterndash BufferedWriter

CET230 -- Razdan et al 24

FileReader constructorFileReader

public FileReader(String fileName) throws FileNotFoundException

Creates a new FileReader given the name of the file to read from

Parameters fileName - the name of the file to read from

Throws FileNotFoundException - if the named file does not exist is a directory rather than a regular file or for some other reason cannot be opened for reading

CET230 -- Razdan et al 25

Read ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )

String s = inreadLine()int i = 1while( s = null )

Systemoutprintln(ldquoLine ldquo + i + ldquo ldquo + s )

i++s = inreadLine()

inclose()

CET230 -- Razdan et al 26

FileWriter constructor

FileWriter

public FileWriter(String fileName) throws IOException Constructs a FileWriter object given a file name

Parameters fileName - String The system-dependent filename

Throws IOException - if the named file exists but is a directory rather than a regular file does not exist but cannot be created or cannot be opened for any other reason

CET230 -- Razdan et al 27

BufferedWriter

Method Summary void

close() Close the stream

voidflush() Flush the stream

voidnewLine() Write a line separator

voidwrite(char[] cbuf int off int len) Write a portion of an array of characters

voidwrite(int c) Write a single character

voidwrite(String s int off int len) Write a portion of a String

CET230 -- Razdan et al 28

Write ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )BufferedWriter out = new BufferedWriter(

new FileWriter(outfile) )

String s = inreadLine()while( s = null )

outwrite((ssplit(ldquosrdquo))[0])outnewLine()s = inreadLine()

inclose()outclose()

CET230 -- Razdan et al 29

Java Interfaces

bull A Java interface is a set of related methods that a programmer may want to support in a single classndash Eg Cloneablendash Eg Comparablehttpjavasuncomj2se150docsapijavalangComparablehtml

CET230 -- Razdan et al 30

Iterator Pattern

bull Motivation ndash an aggregate object should give you a way to access its

elements without exposing its internal structure

ndash Use of the object may want to traverse the object in many different ways ndash donrsquot want to bloat the interface with may traversal methods even if you could anticipate all the methods needed

ndash May need to have more than one traversal pending on the aggregate at once

CET230 -- Razdan et al 31

Iterator Patternbull Key idea take responsibility for access and

traversal out of the object and put it into an iterator object

bull Iterator provides basic ldquonavigationrdquo methods eg ndash Firstndash Nextndash IsDonendash CurrentItem

CET230 -- Razdan et al 32

Map Interface

bull A map is a collection class in which keyvalue pairs may be added A pair can be retrieved or removed by specifying just its key

CET230 -- Razdan et al 33

TreeMap

bull Javarsquos TreeMapltK Vgt implements the map interface in an efficient way in which the keys are required to come from a class (such as String) that implements the Comparable interface

CET230 -- Razdan et al 34

Example

bull From package javautil

bull TreeMapltString Integergt frequencyData

bull String word

bull Integer count

CET230 -- Razdan et al 35

Operations

bull public V get(K key)

bull public V put(K key V value)

bull public boolean containsKey(K key)

bull public SetltKgt keySet()

bull public int size()

bull public void clear()

CET230 -- Razdan et al 36

Iteration

for (String word wordMapkeySet())

hellipprocess this key which is in variable wordhellip

  • Chapter 5 Generic Programming
  • Javarsquos Object type
  • Issues for ADT that hold objects
  • Widening Conversions
  • Narrowing Conversions
  • Wrapper Classes
  • Old vs New
  • Clones amp Deep Clones
  • Fix (kinda) previous
  • Really fix the shallow clone
  • List clone can use Node clone
  • Doubly Linked List
  • Inheritance
  • Other Lists
  • SkipList example from httpepaperpresscom
  • Abstract Classes
  • Abstract List
  • Implement clone in AbstractList
  • Reflection
  • Reflection cont
  • ldquoBionicrdquo Node
  • Revisiting the String class
  • Using Files for IO
  • FileReader constructor
  • Read Example
  • FileWriter constructor
  • BufferedWriter
  • Write Example
  • Java Interfaces
  • Iterator Pattern
  • Slide 31
  • Map Interface
  • TreeMap
  • Example
  • Operations
  • Iteration
Page 10: Chapter 5 Generic Programming Anshuman Razdan Div of Computing Studies razdan@asu.edu razdan/cst230

CET230 -- Razdan et al 10

Really fix the shallow clonebull We still have a problem with the previous code

Nodes hold Object so clones are referencing the same data

bull What wersquod like to do is

bull But this has a problemndash We donrsquot know the actual class that ldquodatardquo belongs to ndash

it might not be Cloneable

bull To fix this check if ldquodatardquo is instanceof Cloneable If so we can do the ldquodeeprdquo clone If not then wersquore stuck with referencing the same ldquodatardquo object

nodeClonesetData(thisgetData()clone())

CET230 -- Razdan et al 11

List clone can use Node clonebull If a Node is Cloneable then the List clone

is pretty easy (all the work is done by the Node)

bull Consider the following (for List clone)

listClonehead = (Node) thisheadclone()

bull Now we just need to set listClonetail How about the followinglistClonetail = (Node) thistailclone()

bull What can we do

CET230 -- Razdan et al 12

Doubly Linked Listbull A doubly linked list allows us to store

references to the next node as well as the previous node

3 2 7 11

headtail

CET230 -- Razdan et al 13

Inheritance

bull A Doubly Linked List ldquois-ardquo List So we should take advantage of the List wersquove already implementedndash DoubleNode extends Nodendash DoubleList extends List

CET230 -- Razdan et al 14

Other Lists

bull Other types of lists are usefulndash Ordered list (elements in list are stored in some

order) Eg numbers are in increasing order strings are in alphabetical order etc

ndash Circular List the ldquoendrdquo of the list refers back to the head

ndash Skip Lists

CET230 -- Razdan et al 15

SkipList example from httpepaperpresscom

CET230 -- Razdan et al 16

Abstract Classesbull A robust implementation for List is to have an

ldquoAbstractListrdquo class from which concrete Lists (Singly Linked Doubly Linked Ordered etc) can be derived

bull An abstract classndash Has at least one abstract method (a method whose

interface is defined but NO implementation is specified by the class)

ndash Cannot be instantiatedndash Can provide implementation for some methodsndash Can provide attributes common to all concrete

subclasses

CET230 -- Razdan et al 17

Abstract List

bull Attributesndash head tail length

bull Methodsndash Constructor getLength equals clone

bull Abstract Methodsndash Add remove clone

CET230 -- Razdan et al 18

Implement clone in AbstractList

bull What Irsquod really like is to implement the clone() in the AbstractList classndash All Lists contain Nodes We donrsquot want to

rewrite the same code for the clone method over and over again in the concrete List classes

ndash Problem what about a DoubleList that contains DoubleNode The AbstractList implementation will not do enoughbecause the Node clone does not do enough

ndash But I WANT it to do enough

CET230 -- Razdan et al 19

Reflectionbull What if we made the Node clone ldquosmarterrdquo

ndash if itrsquos just a Node then do a Node clonendash if itrsquos some other kind of Node then do that

clonendash But the Node doesnrsquot know all the other classes

that extend it

bull Reflection can be used to obtain information about a class its members or its methods

CET230 -- Razdan et al 20

Reflection cont

bull The Class class (see javalang) has methods that enable us to get information about the classndash eg getMethod(String name Class

[] parameterTypes) returns ldquoMethodrdquo

bull The Method class (see javalangreflect) has methods that enable us to get information about the Method and even CALL the methodndash Object invoke(Object obj Object[] args)

CET230 -- Razdan et al 21

ldquoBionicrdquo Nodebull We can modify the Node clone as follows

Node nodeClonetry nodeClone = (Node) superclone() catch( CloneNotSupportedException e ) throw new CloneNotSupportedException()if( thisdata instanceof Cloneable ) try Class c = thisdatagetClass() Method m = cgetMethod( clone null )

nodeClonedata = minvoke( thisdata null ) catch( Exception e ) nodeClonedata = thisdata else nodeClonedata = thisdataif( thisnext = null ) nodeClonenext = (Node) thisnextclone()else nodeClonenext = nullreturn( nodeClone )

CET230 -- Razdan et al 22

Revisiting the String classbull Some useful String methods

ndash charAt( int index)

ndash indexOf( char ch )

ndash indexOf( String str )

ndash split( String regex )

ndash startsWith( String prefix )

ndash substring( int beginIndex int endIndex )

ndash toLowerCase()

ndash toUpperCase()

Note StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code It is recommended that anyone seeking this functionality use the split method of String or the javautilregex package instead

CET230 -- Razdan et al 23

Using Files for IObull Using files for IO is similar to standard IObull For standard input you usually use

ndash InputStreamReaderndash BufferedReader

bull For standard output you usually usendash Systemoutprint or println

bull For file input you can usendash FileReaderndash BufferedReader

bull For file output you can usendash FileWriterndash BufferedWriter

CET230 -- Razdan et al 24

FileReader constructorFileReader

public FileReader(String fileName) throws FileNotFoundException

Creates a new FileReader given the name of the file to read from

Parameters fileName - the name of the file to read from

Throws FileNotFoundException - if the named file does not exist is a directory rather than a regular file or for some other reason cannot be opened for reading

CET230 -- Razdan et al 25

Read ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )

String s = inreadLine()int i = 1while( s = null )

Systemoutprintln(ldquoLine ldquo + i + ldquo ldquo + s )

i++s = inreadLine()

inclose()

CET230 -- Razdan et al 26

FileWriter constructor

FileWriter

public FileWriter(String fileName) throws IOException Constructs a FileWriter object given a file name

Parameters fileName - String The system-dependent filename

Throws IOException - if the named file exists but is a directory rather than a regular file does not exist but cannot be created or cannot be opened for any other reason

CET230 -- Razdan et al 27

BufferedWriter

Method Summary void

close() Close the stream

voidflush() Flush the stream

voidnewLine() Write a line separator

voidwrite(char[] cbuf int off int len) Write a portion of an array of characters

voidwrite(int c) Write a single character

voidwrite(String s int off int len) Write a portion of a String

CET230 -- Razdan et al 28

Write ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )BufferedWriter out = new BufferedWriter(

new FileWriter(outfile) )

String s = inreadLine()while( s = null )

outwrite((ssplit(ldquosrdquo))[0])outnewLine()s = inreadLine()

inclose()outclose()

CET230 -- Razdan et al 29

Java Interfaces

bull A Java interface is a set of related methods that a programmer may want to support in a single classndash Eg Cloneablendash Eg Comparablehttpjavasuncomj2se150docsapijavalangComparablehtml

CET230 -- Razdan et al 30

Iterator Pattern

bull Motivation ndash an aggregate object should give you a way to access its

elements without exposing its internal structure

ndash Use of the object may want to traverse the object in many different ways ndash donrsquot want to bloat the interface with may traversal methods even if you could anticipate all the methods needed

ndash May need to have more than one traversal pending on the aggregate at once

CET230 -- Razdan et al 31

Iterator Patternbull Key idea take responsibility for access and

traversal out of the object and put it into an iterator object

bull Iterator provides basic ldquonavigationrdquo methods eg ndash Firstndash Nextndash IsDonendash CurrentItem

CET230 -- Razdan et al 32

Map Interface

bull A map is a collection class in which keyvalue pairs may be added A pair can be retrieved or removed by specifying just its key

CET230 -- Razdan et al 33

TreeMap

bull Javarsquos TreeMapltK Vgt implements the map interface in an efficient way in which the keys are required to come from a class (such as String) that implements the Comparable interface

CET230 -- Razdan et al 34

Example

bull From package javautil

bull TreeMapltString Integergt frequencyData

bull String word

bull Integer count

CET230 -- Razdan et al 35

Operations

bull public V get(K key)

bull public V put(K key V value)

bull public boolean containsKey(K key)

bull public SetltKgt keySet()

bull public int size()

bull public void clear()

CET230 -- Razdan et al 36

Iteration

for (String word wordMapkeySet())

hellipprocess this key which is in variable wordhellip

  • Chapter 5 Generic Programming
  • Javarsquos Object type
  • Issues for ADT that hold objects
  • Widening Conversions
  • Narrowing Conversions
  • Wrapper Classes
  • Old vs New
  • Clones amp Deep Clones
  • Fix (kinda) previous
  • Really fix the shallow clone
  • List clone can use Node clone
  • Doubly Linked List
  • Inheritance
  • Other Lists
  • SkipList example from httpepaperpresscom
  • Abstract Classes
  • Abstract List
  • Implement clone in AbstractList
  • Reflection
  • Reflection cont
  • ldquoBionicrdquo Node
  • Revisiting the String class
  • Using Files for IO
  • FileReader constructor
  • Read Example
  • FileWriter constructor
  • BufferedWriter
  • Write Example
  • Java Interfaces
  • Iterator Pattern
  • Slide 31
  • Map Interface
  • TreeMap
  • Example
  • Operations
  • Iteration
Page 11: Chapter 5 Generic Programming Anshuman Razdan Div of Computing Studies razdan@asu.edu razdan/cst230

CET230 -- Razdan et al 11

List clone can use Node clonebull If a Node is Cloneable then the List clone

is pretty easy (all the work is done by the Node)

bull Consider the following (for List clone)

listClonehead = (Node) thisheadclone()

bull Now we just need to set listClonetail How about the followinglistClonetail = (Node) thistailclone()

bull What can we do

CET230 -- Razdan et al 12

Doubly Linked Listbull A doubly linked list allows us to store

references to the next node as well as the previous node

3 2 7 11

headtail

CET230 -- Razdan et al 13

Inheritance

bull A Doubly Linked List ldquois-ardquo List So we should take advantage of the List wersquove already implementedndash DoubleNode extends Nodendash DoubleList extends List

CET230 -- Razdan et al 14

Other Lists

bull Other types of lists are usefulndash Ordered list (elements in list are stored in some

order) Eg numbers are in increasing order strings are in alphabetical order etc

ndash Circular List the ldquoendrdquo of the list refers back to the head

ndash Skip Lists

CET230 -- Razdan et al 15

SkipList example from httpepaperpresscom

CET230 -- Razdan et al 16

Abstract Classesbull A robust implementation for List is to have an

ldquoAbstractListrdquo class from which concrete Lists (Singly Linked Doubly Linked Ordered etc) can be derived

bull An abstract classndash Has at least one abstract method (a method whose

interface is defined but NO implementation is specified by the class)

ndash Cannot be instantiatedndash Can provide implementation for some methodsndash Can provide attributes common to all concrete

subclasses

CET230 -- Razdan et al 17

Abstract List

bull Attributesndash head tail length

bull Methodsndash Constructor getLength equals clone

bull Abstract Methodsndash Add remove clone

CET230 -- Razdan et al 18

Implement clone in AbstractList

bull What Irsquod really like is to implement the clone() in the AbstractList classndash All Lists contain Nodes We donrsquot want to

rewrite the same code for the clone method over and over again in the concrete List classes

ndash Problem what about a DoubleList that contains DoubleNode The AbstractList implementation will not do enoughbecause the Node clone does not do enough

ndash But I WANT it to do enough

CET230 -- Razdan et al 19

Reflectionbull What if we made the Node clone ldquosmarterrdquo

ndash if itrsquos just a Node then do a Node clonendash if itrsquos some other kind of Node then do that

clonendash But the Node doesnrsquot know all the other classes

that extend it

bull Reflection can be used to obtain information about a class its members or its methods

CET230 -- Razdan et al 20

Reflection cont

bull The Class class (see javalang) has methods that enable us to get information about the classndash eg getMethod(String name Class

[] parameterTypes) returns ldquoMethodrdquo

bull The Method class (see javalangreflect) has methods that enable us to get information about the Method and even CALL the methodndash Object invoke(Object obj Object[] args)

CET230 -- Razdan et al 21

ldquoBionicrdquo Nodebull We can modify the Node clone as follows

Node nodeClonetry nodeClone = (Node) superclone() catch( CloneNotSupportedException e ) throw new CloneNotSupportedException()if( thisdata instanceof Cloneable ) try Class c = thisdatagetClass() Method m = cgetMethod( clone null )

nodeClonedata = minvoke( thisdata null ) catch( Exception e ) nodeClonedata = thisdata else nodeClonedata = thisdataif( thisnext = null ) nodeClonenext = (Node) thisnextclone()else nodeClonenext = nullreturn( nodeClone )

CET230 -- Razdan et al 22

Revisiting the String classbull Some useful String methods

ndash charAt( int index)

ndash indexOf( char ch )

ndash indexOf( String str )

ndash split( String regex )

ndash startsWith( String prefix )

ndash substring( int beginIndex int endIndex )

ndash toLowerCase()

ndash toUpperCase()

Note StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code It is recommended that anyone seeking this functionality use the split method of String or the javautilregex package instead

CET230 -- Razdan et al 23

Using Files for IObull Using files for IO is similar to standard IObull For standard input you usually use

ndash InputStreamReaderndash BufferedReader

bull For standard output you usually usendash Systemoutprint or println

bull For file input you can usendash FileReaderndash BufferedReader

bull For file output you can usendash FileWriterndash BufferedWriter

CET230 -- Razdan et al 24

FileReader constructorFileReader

public FileReader(String fileName) throws FileNotFoundException

Creates a new FileReader given the name of the file to read from

Parameters fileName - the name of the file to read from

Throws FileNotFoundException - if the named file does not exist is a directory rather than a regular file or for some other reason cannot be opened for reading

CET230 -- Razdan et al 25

Read ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )

String s = inreadLine()int i = 1while( s = null )

Systemoutprintln(ldquoLine ldquo + i + ldquo ldquo + s )

i++s = inreadLine()

inclose()

CET230 -- Razdan et al 26

FileWriter constructor

FileWriter

public FileWriter(String fileName) throws IOException Constructs a FileWriter object given a file name

Parameters fileName - String The system-dependent filename

Throws IOException - if the named file exists but is a directory rather than a regular file does not exist but cannot be created or cannot be opened for any other reason

CET230 -- Razdan et al 27

BufferedWriter

Method Summary void

close() Close the stream

voidflush() Flush the stream

voidnewLine() Write a line separator

voidwrite(char[] cbuf int off int len) Write a portion of an array of characters

voidwrite(int c) Write a single character

voidwrite(String s int off int len) Write a portion of a String

CET230 -- Razdan et al 28

Write ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )BufferedWriter out = new BufferedWriter(

new FileWriter(outfile) )

String s = inreadLine()while( s = null )

outwrite((ssplit(ldquosrdquo))[0])outnewLine()s = inreadLine()

inclose()outclose()

CET230 -- Razdan et al 29

Java Interfaces

bull A Java interface is a set of related methods that a programmer may want to support in a single classndash Eg Cloneablendash Eg Comparablehttpjavasuncomj2se150docsapijavalangComparablehtml

CET230 -- Razdan et al 30

Iterator Pattern

bull Motivation ndash an aggregate object should give you a way to access its

elements without exposing its internal structure

ndash Use of the object may want to traverse the object in many different ways ndash donrsquot want to bloat the interface with may traversal methods even if you could anticipate all the methods needed

ndash May need to have more than one traversal pending on the aggregate at once

CET230 -- Razdan et al 31

Iterator Patternbull Key idea take responsibility for access and

traversal out of the object and put it into an iterator object

bull Iterator provides basic ldquonavigationrdquo methods eg ndash Firstndash Nextndash IsDonendash CurrentItem

CET230 -- Razdan et al 32

Map Interface

bull A map is a collection class in which keyvalue pairs may be added A pair can be retrieved or removed by specifying just its key

CET230 -- Razdan et al 33

TreeMap

bull Javarsquos TreeMapltK Vgt implements the map interface in an efficient way in which the keys are required to come from a class (such as String) that implements the Comparable interface

CET230 -- Razdan et al 34

Example

bull From package javautil

bull TreeMapltString Integergt frequencyData

bull String word

bull Integer count

CET230 -- Razdan et al 35

Operations

bull public V get(K key)

bull public V put(K key V value)

bull public boolean containsKey(K key)

bull public SetltKgt keySet()

bull public int size()

bull public void clear()

CET230 -- Razdan et al 36

Iteration

for (String word wordMapkeySet())

hellipprocess this key which is in variable wordhellip

  • Chapter 5 Generic Programming
  • Javarsquos Object type
  • Issues for ADT that hold objects
  • Widening Conversions
  • Narrowing Conversions
  • Wrapper Classes
  • Old vs New
  • Clones amp Deep Clones
  • Fix (kinda) previous
  • Really fix the shallow clone
  • List clone can use Node clone
  • Doubly Linked List
  • Inheritance
  • Other Lists
  • SkipList example from httpepaperpresscom
  • Abstract Classes
  • Abstract List
  • Implement clone in AbstractList
  • Reflection
  • Reflection cont
  • ldquoBionicrdquo Node
  • Revisiting the String class
  • Using Files for IO
  • FileReader constructor
  • Read Example
  • FileWriter constructor
  • BufferedWriter
  • Write Example
  • Java Interfaces
  • Iterator Pattern
  • Slide 31
  • Map Interface
  • TreeMap
  • Example
  • Operations
  • Iteration
Page 12: Chapter 5 Generic Programming Anshuman Razdan Div of Computing Studies razdan@asu.edu razdan/cst230

CET230 -- Razdan et al 12

Doubly Linked Listbull A doubly linked list allows us to store

references to the next node as well as the previous node

3 2 7 11

headtail

CET230 -- Razdan et al 13

Inheritance

bull A Doubly Linked List ldquois-ardquo List So we should take advantage of the List wersquove already implementedndash DoubleNode extends Nodendash DoubleList extends List

CET230 -- Razdan et al 14

Other Lists

bull Other types of lists are usefulndash Ordered list (elements in list are stored in some

order) Eg numbers are in increasing order strings are in alphabetical order etc

ndash Circular List the ldquoendrdquo of the list refers back to the head

ndash Skip Lists

CET230 -- Razdan et al 15

SkipList example from httpepaperpresscom

CET230 -- Razdan et al 16

Abstract Classesbull A robust implementation for List is to have an

ldquoAbstractListrdquo class from which concrete Lists (Singly Linked Doubly Linked Ordered etc) can be derived

bull An abstract classndash Has at least one abstract method (a method whose

interface is defined but NO implementation is specified by the class)

ndash Cannot be instantiatedndash Can provide implementation for some methodsndash Can provide attributes common to all concrete

subclasses

CET230 -- Razdan et al 17

Abstract List

bull Attributesndash head tail length

bull Methodsndash Constructor getLength equals clone

bull Abstract Methodsndash Add remove clone

CET230 -- Razdan et al 18

Implement clone in AbstractList

bull What Irsquod really like is to implement the clone() in the AbstractList classndash All Lists contain Nodes We donrsquot want to

rewrite the same code for the clone method over and over again in the concrete List classes

ndash Problem what about a DoubleList that contains DoubleNode The AbstractList implementation will not do enoughbecause the Node clone does not do enough

ndash But I WANT it to do enough

CET230 -- Razdan et al 19

Reflectionbull What if we made the Node clone ldquosmarterrdquo

ndash if itrsquos just a Node then do a Node clonendash if itrsquos some other kind of Node then do that

clonendash But the Node doesnrsquot know all the other classes

that extend it

bull Reflection can be used to obtain information about a class its members or its methods

CET230 -- Razdan et al 20

Reflection cont

bull The Class class (see javalang) has methods that enable us to get information about the classndash eg getMethod(String name Class

[] parameterTypes) returns ldquoMethodrdquo

bull The Method class (see javalangreflect) has methods that enable us to get information about the Method and even CALL the methodndash Object invoke(Object obj Object[] args)

CET230 -- Razdan et al 21

ldquoBionicrdquo Nodebull We can modify the Node clone as follows

Node nodeClonetry nodeClone = (Node) superclone() catch( CloneNotSupportedException e ) throw new CloneNotSupportedException()if( thisdata instanceof Cloneable ) try Class c = thisdatagetClass() Method m = cgetMethod( clone null )

nodeClonedata = minvoke( thisdata null ) catch( Exception e ) nodeClonedata = thisdata else nodeClonedata = thisdataif( thisnext = null ) nodeClonenext = (Node) thisnextclone()else nodeClonenext = nullreturn( nodeClone )

CET230 -- Razdan et al 22

Revisiting the String classbull Some useful String methods

ndash charAt( int index)

ndash indexOf( char ch )

ndash indexOf( String str )

ndash split( String regex )

ndash startsWith( String prefix )

ndash substring( int beginIndex int endIndex )

ndash toLowerCase()

ndash toUpperCase()

Note StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code It is recommended that anyone seeking this functionality use the split method of String or the javautilregex package instead

CET230 -- Razdan et al 23

Using Files for IObull Using files for IO is similar to standard IObull For standard input you usually use

ndash InputStreamReaderndash BufferedReader

bull For standard output you usually usendash Systemoutprint or println

bull For file input you can usendash FileReaderndash BufferedReader

bull For file output you can usendash FileWriterndash BufferedWriter

CET230 -- Razdan et al 24

FileReader constructorFileReader

public FileReader(String fileName) throws FileNotFoundException

Creates a new FileReader given the name of the file to read from

Parameters fileName - the name of the file to read from

Throws FileNotFoundException - if the named file does not exist is a directory rather than a regular file or for some other reason cannot be opened for reading

CET230 -- Razdan et al 25

Read ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )

String s = inreadLine()int i = 1while( s = null )

Systemoutprintln(ldquoLine ldquo + i + ldquo ldquo + s )

i++s = inreadLine()

inclose()

CET230 -- Razdan et al 26

FileWriter constructor

FileWriter

public FileWriter(String fileName) throws IOException Constructs a FileWriter object given a file name

Parameters fileName - String The system-dependent filename

Throws IOException - if the named file exists but is a directory rather than a regular file does not exist but cannot be created or cannot be opened for any other reason

CET230 -- Razdan et al 27

BufferedWriter

Method Summary void

close() Close the stream

voidflush() Flush the stream

voidnewLine() Write a line separator

voidwrite(char[] cbuf int off int len) Write a portion of an array of characters

voidwrite(int c) Write a single character

voidwrite(String s int off int len) Write a portion of a String

CET230 -- Razdan et al 28

Write ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )BufferedWriter out = new BufferedWriter(

new FileWriter(outfile) )

String s = inreadLine()while( s = null )

outwrite((ssplit(ldquosrdquo))[0])outnewLine()s = inreadLine()

inclose()outclose()

CET230 -- Razdan et al 29

Java Interfaces

bull A Java interface is a set of related methods that a programmer may want to support in a single classndash Eg Cloneablendash Eg Comparablehttpjavasuncomj2se150docsapijavalangComparablehtml

CET230 -- Razdan et al 30

Iterator Pattern

bull Motivation ndash an aggregate object should give you a way to access its

elements without exposing its internal structure

ndash Use of the object may want to traverse the object in many different ways ndash donrsquot want to bloat the interface with may traversal methods even if you could anticipate all the methods needed

ndash May need to have more than one traversal pending on the aggregate at once

CET230 -- Razdan et al 31

Iterator Patternbull Key idea take responsibility for access and

traversal out of the object and put it into an iterator object

bull Iterator provides basic ldquonavigationrdquo methods eg ndash Firstndash Nextndash IsDonendash CurrentItem

CET230 -- Razdan et al 32

Map Interface

bull A map is a collection class in which keyvalue pairs may be added A pair can be retrieved or removed by specifying just its key

CET230 -- Razdan et al 33

TreeMap

bull Javarsquos TreeMapltK Vgt implements the map interface in an efficient way in which the keys are required to come from a class (such as String) that implements the Comparable interface

CET230 -- Razdan et al 34

Example

bull From package javautil

bull TreeMapltString Integergt frequencyData

bull String word

bull Integer count

CET230 -- Razdan et al 35

Operations

bull public V get(K key)

bull public V put(K key V value)

bull public boolean containsKey(K key)

bull public SetltKgt keySet()

bull public int size()

bull public void clear()

CET230 -- Razdan et al 36

Iteration

for (String word wordMapkeySet())

hellipprocess this key which is in variable wordhellip

  • Chapter 5 Generic Programming
  • Javarsquos Object type
  • Issues for ADT that hold objects
  • Widening Conversions
  • Narrowing Conversions
  • Wrapper Classes
  • Old vs New
  • Clones amp Deep Clones
  • Fix (kinda) previous
  • Really fix the shallow clone
  • List clone can use Node clone
  • Doubly Linked List
  • Inheritance
  • Other Lists
  • SkipList example from httpepaperpresscom
  • Abstract Classes
  • Abstract List
  • Implement clone in AbstractList
  • Reflection
  • Reflection cont
  • ldquoBionicrdquo Node
  • Revisiting the String class
  • Using Files for IO
  • FileReader constructor
  • Read Example
  • FileWriter constructor
  • BufferedWriter
  • Write Example
  • Java Interfaces
  • Iterator Pattern
  • Slide 31
  • Map Interface
  • TreeMap
  • Example
  • Operations
  • Iteration
Page 13: Chapter 5 Generic Programming Anshuman Razdan Div of Computing Studies razdan@asu.edu razdan/cst230

CET230 -- Razdan et al 13

Inheritance

bull A Doubly Linked List ldquois-ardquo List So we should take advantage of the List wersquove already implementedndash DoubleNode extends Nodendash DoubleList extends List

CET230 -- Razdan et al 14

Other Lists

bull Other types of lists are usefulndash Ordered list (elements in list are stored in some

order) Eg numbers are in increasing order strings are in alphabetical order etc

ndash Circular List the ldquoendrdquo of the list refers back to the head

ndash Skip Lists

CET230 -- Razdan et al 15

SkipList example from httpepaperpresscom

CET230 -- Razdan et al 16

Abstract Classesbull A robust implementation for List is to have an

ldquoAbstractListrdquo class from which concrete Lists (Singly Linked Doubly Linked Ordered etc) can be derived

bull An abstract classndash Has at least one abstract method (a method whose

interface is defined but NO implementation is specified by the class)

ndash Cannot be instantiatedndash Can provide implementation for some methodsndash Can provide attributes common to all concrete

subclasses

CET230 -- Razdan et al 17

Abstract List

bull Attributesndash head tail length

bull Methodsndash Constructor getLength equals clone

bull Abstract Methodsndash Add remove clone

CET230 -- Razdan et al 18

Implement clone in AbstractList

bull What Irsquod really like is to implement the clone() in the AbstractList classndash All Lists contain Nodes We donrsquot want to

rewrite the same code for the clone method over and over again in the concrete List classes

ndash Problem what about a DoubleList that contains DoubleNode The AbstractList implementation will not do enoughbecause the Node clone does not do enough

ndash But I WANT it to do enough

CET230 -- Razdan et al 19

Reflectionbull What if we made the Node clone ldquosmarterrdquo

ndash if itrsquos just a Node then do a Node clonendash if itrsquos some other kind of Node then do that

clonendash But the Node doesnrsquot know all the other classes

that extend it

bull Reflection can be used to obtain information about a class its members or its methods

CET230 -- Razdan et al 20

Reflection cont

bull The Class class (see javalang) has methods that enable us to get information about the classndash eg getMethod(String name Class

[] parameterTypes) returns ldquoMethodrdquo

bull The Method class (see javalangreflect) has methods that enable us to get information about the Method and even CALL the methodndash Object invoke(Object obj Object[] args)

CET230 -- Razdan et al 21

ldquoBionicrdquo Nodebull We can modify the Node clone as follows

Node nodeClonetry nodeClone = (Node) superclone() catch( CloneNotSupportedException e ) throw new CloneNotSupportedException()if( thisdata instanceof Cloneable ) try Class c = thisdatagetClass() Method m = cgetMethod( clone null )

nodeClonedata = minvoke( thisdata null ) catch( Exception e ) nodeClonedata = thisdata else nodeClonedata = thisdataif( thisnext = null ) nodeClonenext = (Node) thisnextclone()else nodeClonenext = nullreturn( nodeClone )

CET230 -- Razdan et al 22

Revisiting the String classbull Some useful String methods

ndash charAt( int index)

ndash indexOf( char ch )

ndash indexOf( String str )

ndash split( String regex )

ndash startsWith( String prefix )

ndash substring( int beginIndex int endIndex )

ndash toLowerCase()

ndash toUpperCase()

Note StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code It is recommended that anyone seeking this functionality use the split method of String or the javautilregex package instead

CET230 -- Razdan et al 23

Using Files for IObull Using files for IO is similar to standard IObull For standard input you usually use

ndash InputStreamReaderndash BufferedReader

bull For standard output you usually usendash Systemoutprint or println

bull For file input you can usendash FileReaderndash BufferedReader

bull For file output you can usendash FileWriterndash BufferedWriter

CET230 -- Razdan et al 24

FileReader constructorFileReader

public FileReader(String fileName) throws FileNotFoundException

Creates a new FileReader given the name of the file to read from

Parameters fileName - the name of the file to read from

Throws FileNotFoundException - if the named file does not exist is a directory rather than a regular file or for some other reason cannot be opened for reading

CET230 -- Razdan et al 25

Read ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )

String s = inreadLine()int i = 1while( s = null )

Systemoutprintln(ldquoLine ldquo + i + ldquo ldquo + s )

i++s = inreadLine()

inclose()

CET230 -- Razdan et al 26

FileWriter constructor

FileWriter

public FileWriter(String fileName) throws IOException Constructs a FileWriter object given a file name

Parameters fileName - String The system-dependent filename

Throws IOException - if the named file exists but is a directory rather than a regular file does not exist but cannot be created or cannot be opened for any other reason

CET230 -- Razdan et al 27

BufferedWriter

Method Summary void

close() Close the stream

voidflush() Flush the stream

voidnewLine() Write a line separator

voidwrite(char[] cbuf int off int len) Write a portion of an array of characters

voidwrite(int c) Write a single character

voidwrite(String s int off int len) Write a portion of a String

CET230 -- Razdan et al 28

Write ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )BufferedWriter out = new BufferedWriter(

new FileWriter(outfile) )

String s = inreadLine()while( s = null )

outwrite((ssplit(ldquosrdquo))[0])outnewLine()s = inreadLine()

inclose()outclose()

CET230 -- Razdan et al 29

Java Interfaces

bull A Java interface is a set of related methods that a programmer may want to support in a single classndash Eg Cloneablendash Eg Comparablehttpjavasuncomj2se150docsapijavalangComparablehtml

CET230 -- Razdan et al 30

Iterator Pattern

bull Motivation ndash an aggregate object should give you a way to access its

elements without exposing its internal structure

ndash Use of the object may want to traverse the object in many different ways ndash donrsquot want to bloat the interface with may traversal methods even if you could anticipate all the methods needed

ndash May need to have more than one traversal pending on the aggregate at once

CET230 -- Razdan et al 31

Iterator Patternbull Key idea take responsibility for access and

traversal out of the object and put it into an iterator object

bull Iterator provides basic ldquonavigationrdquo methods eg ndash Firstndash Nextndash IsDonendash CurrentItem

CET230 -- Razdan et al 32

Map Interface

bull A map is a collection class in which keyvalue pairs may be added A pair can be retrieved or removed by specifying just its key

CET230 -- Razdan et al 33

TreeMap

bull Javarsquos TreeMapltK Vgt implements the map interface in an efficient way in which the keys are required to come from a class (such as String) that implements the Comparable interface

CET230 -- Razdan et al 34

Example

bull From package javautil

bull TreeMapltString Integergt frequencyData

bull String word

bull Integer count

CET230 -- Razdan et al 35

Operations

bull public V get(K key)

bull public V put(K key V value)

bull public boolean containsKey(K key)

bull public SetltKgt keySet()

bull public int size()

bull public void clear()

CET230 -- Razdan et al 36

Iteration

for (String word wordMapkeySet())

hellipprocess this key which is in variable wordhellip

  • Chapter 5 Generic Programming
  • Javarsquos Object type
  • Issues for ADT that hold objects
  • Widening Conversions
  • Narrowing Conversions
  • Wrapper Classes
  • Old vs New
  • Clones amp Deep Clones
  • Fix (kinda) previous
  • Really fix the shallow clone
  • List clone can use Node clone
  • Doubly Linked List
  • Inheritance
  • Other Lists
  • SkipList example from httpepaperpresscom
  • Abstract Classes
  • Abstract List
  • Implement clone in AbstractList
  • Reflection
  • Reflection cont
  • ldquoBionicrdquo Node
  • Revisiting the String class
  • Using Files for IO
  • FileReader constructor
  • Read Example
  • FileWriter constructor
  • BufferedWriter
  • Write Example
  • Java Interfaces
  • Iterator Pattern
  • Slide 31
  • Map Interface
  • TreeMap
  • Example
  • Operations
  • Iteration
Page 14: Chapter 5 Generic Programming Anshuman Razdan Div of Computing Studies razdan@asu.edu razdan/cst230

CET230 -- Razdan et al 14

Other Lists

bull Other types of lists are usefulndash Ordered list (elements in list are stored in some

order) Eg numbers are in increasing order strings are in alphabetical order etc

ndash Circular List the ldquoendrdquo of the list refers back to the head

ndash Skip Lists

CET230 -- Razdan et al 15

SkipList example from httpepaperpresscom

CET230 -- Razdan et al 16

Abstract Classesbull A robust implementation for List is to have an

ldquoAbstractListrdquo class from which concrete Lists (Singly Linked Doubly Linked Ordered etc) can be derived

bull An abstract classndash Has at least one abstract method (a method whose

interface is defined but NO implementation is specified by the class)

ndash Cannot be instantiatedndash Can provide implementation for some methodsndash Can provide attributes common to all concrete

subclasses

CET230 -- Razdan et al 17

Abstract List

bull Attributesndash head tail length

bull Methodsndash Constructor getLength equals clone

bull Abstract Methodsndash Add remove clone

CET230 -- Razdan et al 18

Implement clone in AbstractList

bull What Irsquod really like is to implement the clone() in the AbstractList classndash All Lists contain Nodes We donrsquot want to

rewrite the same code for the clone method over and over again in the concrete List classes

ndash Problem what about a DoubleList that contains DoubleNode The AbstractList implementation will not do enoughbecause the Node clone does not do enough

ndash But I WANT it to do enough

CET230 -- Razdan et al 19

Reflectionbull What if we made the Node clone ldquosmarterrdquo

ndash if itrsquos just a Node then do a Node clonendash if itrsquos some other kind of Node then do that

clonendash But the Node doesnrsquot know all the other classes

that extend it

bull Reflection can be used to obtain information about a class its members or its methods

CET230 -- Razdan et al 20

Reflection cont

bull The Class class (see javalang) has methods that enable us to get information about the classndash eg getMethod(String name Class

[] parameterTypes) returns ldquoMethodrdquo

bull The Method class (see javalangreflect) has methods that enable us to get information about the Method and even CALL the methodndash Object invoke(Object obj Object[] args)

CET230 -- Razdan et al 21

ldquoBionicrdquo Nodebull We can modify the Node clone as follows

Node nodeClonetry nodeClone = (Node) superclone() catch( CloneNotSupportedException e ) throw new CloneNotSupportedException()if( thisdata instanceof Cloneable ) try Class c = thisdatagetClass() Method m = cgetMethod( clone null )

nodeClonedata = minvoke( thisdata null ) catch( Exception e ) nodeClonedata = thisdata else nodeClonedata = thisdataif( thisnext = null ) nodeClonenext = (Node) thisnextclone()else nodeClonenext = nullreturn( nodeClone )

CET230 -- Razdan et al 22

Revisiting the String classbull Some useful String methods

ndash charAt( int index)

ndash indexOf( char ch )

ndash indexOf( String str )

ndash split( String regex )

ndash startsWith( String prefix )

ndash substring( int beginIndex int endIndex )

ndash toLowerCase()

ndash toUpperCase()

Note StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code It is recommended that anyone seeking this functionality use the split method of String or the javautilregex package instead

CET230 -- Razdan et al 23

Using Files for IObull Using files for IO is similar to standard IObull For standard input you usually use

ndash InputStreamReaderndash BufferedReader

bull For standard output you usually usendash Systemoutprint or println

bull For file input you can usendash FileReaderndash BufferedReader

bull For file output you can usendash FileWriterndash BufferedWriter

CET230 -- Razdan et al 24

FileReader constructorFileReader

public FileReader(String fileName) throws FileNotFoundException

Creates a new FileReader given the name of the file to read from

Parameters fileName - the name of the file to read from

Throws FileNotFoundException - if the named file does not exist is a directory rather than a regular file or for some other reason cannot be opened for reading

CET230 -- Razdan et al 25

Read ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )

String s = inreadLine()int i = 1while( s = null )

Systemoutprintln(ldquoLine ldquo + i + ldquo ldquo + s )

i++s = inreadLine()

inclose()

CET230 -- Razdan et al 26

FileWriter constructor

FileWriter

public FileWriter(String fileName) throws IOException Constructs a FileWriter object given a file name

Parameters fileName - String The system-dependent filename

Throws IOException - if the named file exists but is a directory rather than a regular file does not exist but cannot be created or cannot be opened for any other reason

CET230 -- Razdan et al 27

BufferedWriter

Method Summary void

close() Close the stream

voidflush() Flush the stream

voidnewLine() Write a line separator

voidwrite(char[] cbuf int off int len) Write a portion of an array of characters

voidwrite(int c) Write a single character

voidwrite(String s int off int len) Write a portion of a String

CET230 -- Razdan et al 28

Write ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )BufferedWriter out = new BufferedWriter(

new FileWriter(outfile) )

String s = inreadLine()while( s = null )

outwrite((ssplit(ldquosrdquo))[0])outnewLine()s = inreadLine()

inclose()outclose()

CET230 -- Razdan et al 29

Java Interfaces

bull A Java interface is a set of related methods that a programmer may want to support in a single classndash Eg Cloneablendash Eg Comparablehttpjavasuncomj2se150docsapijavalangComparablehtml

CET230 -- Razdan et al 30

Iterator Pattern

bull Motivation ndash an aggregate object should give you a way to access its

elements without exposing its internal structure

ndash Use of the object may want to traverse the object in many different ways ndash donrsquot want to bloat the interface with may traversal methods even if you could anticipate all the methods needed

ndash May need to have more than one traversal pending on the aggregate at once

CET230 -- Razdan et al 31

Iterator Patternbull Key idea take responsibility for access and

traversal out of the object and put it into an iterator object

bull Iterator provides basic ldquonavigationrdquo methods eg ndash Firstndash Nextndash IsDonendash CurrentItem

CET230 -- Razdan et al 32

Map Interface

bull A map is a collection class in which keyvalue pairs may be added A pair can be retrieved or removed by specifying just its key

CET230 -- Razdan et al 33

TreeMap

bull Javarsquos TreeMapltK Vgt implements the map interface in an efficient way in which the keys are required to come from a class (such as String) that implements the Comparable interface

CET230 -- Razdan et al 34

Example

bull From package javautil

bull TreeMapltString Integergt frequencyData

bull String word

bull Integer count

CET230 -- Razdan et al 35

Operations

bull public V get(K key)

bull public V put(K key V value)

bull public boolean containsKey(K key)

bull public SetltKgt keySet()

bull public int size()

bull public void clear()

CET230 -- Razdan et al 36

Iteration

for (String word wordMapkeySet())

hellipprocess this key which is in variable wordhellip

  • Chapter 5 Generic Programming
  • Javarsquos Object type
  • Issues for ADT that hold objects
  • Widening Conversions
  • Narrowing Conversions
  • Wrapper Classes
  • Old vs New
  • Clones amp Deep Clones
  • Fix (kinda) previous
  • Really fix the shallow clone
  • List clone can use Node clone
  • Doubly Linked List
  • Inheritance
  • Other Lists
  • SkipList example from httpepaperpresscom
  • Abstract Classes
  • Abstract List
  • Implement clone in AbstractList
  • Reflection
  • Reflection cont
  • ldquoBionicrdquo Node
  • Revisiting the String class
  • Using Files for IO
  • FileReader constructor
  • Read Example
  • FileWriter constructor
  • BufferedWriter
  • Write Example
  • Java Interfaces
  • Iterator Pattern
  • Slide 31
  • Map Interface
  • TreeMap
  • Example
  • Operations
  • Iteration
Page 15: Chapter 5 Generic Programming Anshuman Razdan Div of Computing Studies razdan@asu.edu razdan/cst230

CET230 -- Razdan et al 15

SkipList example from httpepaperpresscom

CET230 -- Razdan et al 16

Abstract Classesbull A robust implementation for List is to have an

ldquoAbstractListrdquo class from which concrete Lists (Singly Linked Doubly Linked Ordered etc) can be derived

bull An abstract classndash Has at least one abstract method (a method whose

interface is defined but NO implementation is specified by the class)

ndash Cannot be instantiatedndash Can provide implementation for some methodsndash Can provide attributes common to all concrete

subclasses

CET230 -- Razdan et al 17

Abstract List

bull Attributesndash head tail length

bull Methodsndash Constructor getLength equals clone

bull Abstract Methodsndash Add remove clone

CET230 -- Razdan et al 18

Implement clone in AbstractList

bull What Irsquod really like is to implement the clone() in the AbstractList classndash All Lists contain Nodes We donrsquot want to

rewrite the same code for the clone method over and over again in the concrete List classes

ndash Problem what about a DoubleList that contains DoubleNode The AbstractList implementation will not do enoughbecause the Node clone does not do enough

ndash But I WANT it to do enough

CET230 -- Razdan et al 19

Reflectionbull What if we made the Node clone ldquosmarterrdquo

ndash if itrsquos just a Node then do a Node clonendash if itrsquos some other kind of Node then do that

clonendash But the Node doesnrsquot know all the other classes

that extend it

bull Reflection can be used to obtain information about a class its members or its methods

CET230 -- Razdan et al 20

Reflection cont

bull The Class class (see javalang) has methods that enable us to get information about the classndash eg getMethod(String name Class

[] parameterTypes) returns ldquoMethodrdquo

bull The Method class (see javalangreflect) has methods that enable us to get information about the Method and even CALL the methodndash Object invoke(Object obj Object[] args)

CET230 -- Razdan et al 21

ldquoBionicrdquo Nodebull We can modify the Node clone as follows

Node nodeClonetry nodeClone = (Node) superclone() catch( CloneNotSupportedException e ) throw new CloneNotSupportedException()if( thisdata instanceof Cloneable ) try Class c = thisdatagetClass() Method m = cgetMethod( clone null )

nodeClonedata = minvoke( thisdata null ) catch( Exception e ) nodeClonedata = thisdata else nodeClonedata = thisdataif( thisnext = null ) nodeClonenext = (Node) thisnextclone()else nodeClonenext = nullreturn( nodeClone )

CET230 -- Razdan et al 22

Revisiting the String classbull Some useful String methods

ndash charAt( int index)

ndash indexOf( char ch )

ndash indexOf( String str )

ndash split( String regex )

ndash startsWith( String prefix )

ndash substring( int beginIndex int endIndex )

ndash toLowerCase()

ndash toUpperCase()

Note StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code It is recommended that anyone seeking this functionality use the split method of String or the javautilregex package instead

CET230 -- Razdan et al 23

Using Files for IObull Using files for IO is similar to standard IObull For standard input you usually use

ndash InputStreamReaderndash BufferedReader

bull For standard output you usually usendash Systemoutprint or println

bull For file input you can usendash FileReaderndash BufferedReader

bull For file output you can usendash FileWriterndash BufferedWriter

CET230 -- Razdan et al 24

FileReader constructorFileReader

public FileReader(String fileName) throws FileNotFoundException

Creates a new FileReader given the name of the file to read from

Parameters fileName - the name of the file to read from

Throws FileNotFoundException - if the named file does not exist is a directory rather than a regular file or for some other reason cannot be opened for reading

CET230 -- Razdan et al 25

Read ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )

String s = inreadLine()int i = 1while( s = null )

Systemoutprintln(ldquoLine ldquo + i + ldquo ldquo + s )

i++s = inreadLine()

inclose()

CET230 -- Razdan et al 26

FileWriter constructor

FileWriter

public FileWriter(String fileName) throws IOException Constructs a FileWriter object given a file name

Parameters fileName - String The system-dependent filename

Throws IOException - if the named file exists but is a directory rather than a regular file does not exist but cannot be created or cannot be opened for any other reason

CET230 -- Razdan et al 27

BufferedWriter

Method Summary void

close() Close the stream

voidflush() Flush the stream

voidnewLine() Write a line separator

voidwrite(char[] cbuf int off int len) Write a portion of an array of characters

voidwrite(int c) Write a single character

voidwrite(String s int off int len) Write a portion of a String

CET230 -- Razdan et al 28

Write ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )BufferedWriter out = new BufferedWriter(

new FileWriter(outfile) )

String s = inreadLine()while( s = null )

outwrite((ssplit(ldquosrdquo))[0])outnewLine()s = inreadLine()

inclose()outclose()

CET230 -- Razdan et al 29

Java Interfaces

bull A Java interface is a set of related methods that a programmer may want to support in a single classndash Eg Cloneablendash Eg Comparablehttpjavasuncomj2se150docsapijavalangComparablehtml

CET230 -- Razdan et al 30

Iterator Pattern

bull Motivation ndash an aggregate object should give you a way to access its

elements without exposing its internal structure

ndash Use of the object may want to traverse the object in many different ways ndash donrsquot want to bloat the interface with may traversal methods even if you could anticipate all the methods needed

ndash May need to have more than one traversal pending on the aggregate at once

CET230 -- Razdan et al 31

Iterator Patternbull Key idea take responsibility for access and

traversal out of the object and put it into an iterator object

bull Iterator provides basic ldquonavigationrdquo methods eg ndash Firstndash Nextndash IsDonendash CurrentItem

CET230 -- Razdan et al 32

Map Interface

bull A map is a collection class in which keyvalue pairs may be added A pair can be retrieved or removed by specifying just its key

CET230 -- Razdan et al 33

TreeMap

bull Javarsquos TreeMapltK Vgt implements the map interface in an efficient way in which the keys are required to come from a class (such as String) that implements the Comparable interface

CET230 -- Razdan et al 34

Example

bull From package javautil

bull TreeMapltString Integergt frequencyData

bull String word

bull Integer count

CET230 -- Razdan et al 35

Operations

bull public V get(K key)

bull public V put(K key V value)

bull public boolean containsKey(K key)

bull public SetltKgt keySet()

bull public int size()

bull public void clear()

CET230 -- Razdan et al 36

Iteration

for (String word wordMapkeySet())

hellipprocess this key which is in variable wordhellip

  • Chapter 5 Generic Programming
  • Javarsquos Object type
  • Issues for ADT that hold objects
  • Widening Conversions
  • Narrowing Conversions
  • Wrapper Classes
  • Old vs New
  • Clones amp Deep Clones
  • Fix (kinda) previous
  • Really fix the shallow clone
  • List clone can use Node clone
  • Doubly Linked List
  • Inheritance
  • Other Lists
  • SkipList example from httpepaperpresscom
  • Abstract Classes
  • Abstract List
  • Implement clone in AbstractList
  • Reflection
  • Reflection cont
  • ldquoBionicrdquo Node
  • Revisiting the String class
  • Using Files for IO
  • FileReader constructor
  • Read Example
  • FileWriter constructor
  • BufferedWriter
  • Write Example
  • Java Interfaces
  • Iterator Pattern
  • Slide 31
  • Map Interface
  • TreeMap
  • Example
  • Operations
  • Iteration
Page 16: Chapter 5 Generic Programming Anshuman Razdan Div of Computing Studies razdan@asu.edu razdan/cst230

CET230 -- Razdan et al 16

Abstract Classesbull A robust implementation for List is to have an

ldquoAbstractListrdquo class from which concrete Lists (Singly Linked Doubly Linked Ordered etc) can be derived

bull An abstract classndash Has at least one abstract method (a method whose

interface is defined but NO implementation is specified by the class)

ndash Cannot be instantiatedndash Can provide implementation for some methodsndash Can provide attributes common to all concrete

subclasses

CET230 -- Razdan et al 17

Abstract List

bull Attributesndash head tail length

bull Methodsndash Constructor getLength equals clone

bull Abstract Methodsndash Add remove clone

CET230 -- Razdan et al 18

Implement clone in AbstractList

bull What Irsquod really like is to implement the clone() in the AbstractList classndash All Lists contain Nodes We donrsquot want to

rewrite the same code for the clone method over and over again in the concrete List classes

ndash Problem what about a DoubleList that contains DoubleNode The AbstractList implementation will not do enoughbecause the Node clone does not do enough

ndash But I WANT it to do enough

CET230 -- Razdan et al 19

Reflectionbull What if we made the Node clone ldquosmarterrdquo

ndash if itrsquos just a Node then do a Node clonendash if itrsquos some other kind of Node then do that

clonendash But the Node doesnrsquot know all the other classes

that extend it

bull Reflection can be used to obtain information about a class its members or its methods

CET230 -- Razdan et al 20

Reflection cont

bull The Class class (see javalang) has methods that enable us to get information about the classndash eg getMethod(String name Class

[] parameterTypes) returns ldquoMethodrdquo

bull The Method class (see javalangreflect) has methods that enable us to get information about the Method and even CALL the methodndash Object invoke(Object obj Object[] args)

CET230 -- Razdan et al 21

ldquoBionicrdquo Nodebull We can modify the Node clone as follows

Node nodeClonetry nodeClone = (Node) superclone() catch( CloneNotSupportedException e ) throw new CloneNotSupportedException()if( thisdata instanceof Cloneable ) try Class c = thisdatagetClass() Method m = cgetMethod( clone null )

nodeClonedata = minvoke( thisdata null ) catch( Exception e ) nodeClonedata = thisdata else nodeClonedata = thisdataif( thisnext = null ) nodeClonenext = (Node) thisnextclone()else nodeClonenext = nullreturn( nodeClone )

CET230 -- Razdan et al 22

Revisiting the String classbull Some useful String methods

ndash charAt( int index)

ndash indexOf( char ch )

ndash indexOf( String str )

ndash split( String regex )

ndash startsWith( String prefix )

ndash substring( int beginIndex int endIndex )

ndash toLowerCase()

ndash toUpperCase()

Note StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code It is recommended that anyone seeking this functionality use the split method of String or the javautilregex package instead

CET230 -- Razdan et al 23

Using Files for IObull Using files for IO is similar to standard IObull For standard input you usually use

ndash InputStreamReaderndash BufferedReader

bull For standard output you usually usendash Systemoutprint or println

bull For file input you can usendash FileReaderndash BufferedReader

bull For file output you can usendash FileWriterndash BufferedWriter

CET230 -- Razdan et al 24

FileReader constructorFileReader

public FileReader(String fileName) throws FileNotFoundException

Creates a new FileReader given the name of the file to read from

Parameters fileName - the name of the file to read from

Throws FileNotFoundException - if the named file does not exist is a directory rather than a regular file or for some other reason cannot be opened for reading

CET230 -- Razdan et al 25

Read ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )

String s = inreadLine()int i = 1while( s = null )

Systemoutprintln(ldquoLine ldquo + i + ldquo ldquo + s )

i++s = inreadLine()

inclose()

CET230 -- Razdan et al 26

FileWriter constructor

FileWriter

public FileWriter(String fileName) throws IOException Constructs a FileWriter object given a file name

Parameters fileName - String The system-dependent filename

Throws IOException - if the named file exists but is a directory rather than a regular file does not exist but cannot be created or cannot be opened for any other reason

CET230 -- Razdan et al 27

BufferedWriter

Method Summary void

close() Close the stream

voidflush() Flush the stream

voidnewLine() Write a line separator

voidwrite(char[] cbuf int off int len) Write a portion of an array of characters

voidwrite(int c) Write a single character

voidwrite(String s int off int len) Write a portion of a String

CET230 -- Razdan et al 28

Write ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )BufferedWriter out = new BufferedWriter(

new FileWriter(outfile) )

String s = inreadLine()while( s = null )

outwrite((ssplit(ldquosrdquo))[0])outnewLine()s = inreadLine()

inclose()outclose()

CET230 -- Razdan et al 29

Java Interfaces

bull A Java interface is a set of related methods that a programmer may want to support in a single classndash Eg Cloneablendash Eg Comparablehttpjavasuncomj2se150docsapijavalangComparablehtml

CET230 -- Razdan et al 30

Iterator Pattern

bull Motivation ndash an aggregate object should give you a way to access its

elements without exposing its internal structure

ndash Use of the object may want to traverse the object in many different ways ndash donrsquot want to bloat the interface with may traversal methods even if you could anticipate all the methods needed

ndash May need to have more than one traversal pending on the aggregate at once

CET230 -- Razdan et al 31

Iterator Patternbull Key idea take responsibility for access and

traversal out of the object and put it into an iterator object

bull Iterator provides basic ldquonavigationrdquo methods eg ndash Firstndash Nextndash IsDonendash CurrentItem

CET230 -- Razdan et al 32

Map Interface

bull A map is a collection class in which keyvalue pairs may be added A pair can be retrieved or removed by specifying just its key

CET230 -- Razdan et al 33

TreeMap

bull Javarsquos TreeMapltK Vgt implements the map interface in an efficient way in which the keys are required to come from a class (such as String) that implements the Comparable interface

CET230 -- Razdan et al 34

Example

bull From package javautil

bull TreeMapltString Integergt frequencyData

bull String word

bull Integer count

CET230 -- Razdan et al 35

Operations

bull public V get(K key)

bull public V put(K key V value)

bull public boolean containsKey(K key)

bull public SetltKgt keySet()

bull public int size()

bull public void clear()

CET230 -- Razdan et al 36

Iteration

for (String word wordMapkeySet())

hellipprocess this key which is in variable wordhellip

  • Chapter 5 Generic Programming
  • Javarsquos Object type
  • Issues for ADT that hold objects
  • Widening Conversions
  • Narrowing Conversions
  • Wrapper Classes
  • Old vs New
  • Clones amp Deep Clones
  • Fix (kinda) previous
  • Really fix the shallow clone
  • List clone can use Node clone
  • Doubly Linked List
  • Inheritance
  • Other Lists
  • SkipList example from httpepaperpresscom
  • Abstract Classes
  • Abstract List
  • Implement clone in AbstractList
  • Reflection
  • Reflection cont
  • ldquoBionicrdquo Node
  • Revisiting the String class
  • Using Files for IO
  • FileReader constructor
  • Read Example
  • FileWriter constructor
  • BufferedWriter
  • Write Example
  • Java Interfaces
  • Iterator Pattern
  • Slide 31
  • Map Interface
  • TreeMap
  • Example
  • Operations
  • Iteration
Page 17: Chapter 5 Generic Programming Anshuman Razdan Div of Computing Studies razdan@asu.edu razdan/cst230

CET230 -- Razdan et al 17

Abstract List

bull Attributesndash head tail length

bull Methodsndash Constructor getLength equals clone

bull Abstract Methodsndash Add remove clone

CET230 -- Razdan et al 18

Implement clone in AbstractList

bull What Irsquod really like is to implement the clone() in the AbstractList classndash All Lists contain Nodes We donrsquot want to

rewrite the same code for the clone method over and over again in the concrete List classes

ndash Problem what about a DoubleList that contains DoubleNode The AbstractList implementation will not do enoughbecause the Node clone does not do enough

ndash But I WANT it to do enough

CET230 -- Razdan et al 19

Reflectionbull What if we made the Node clone ldquosmarterrdquo

ndash if itrsquos just a Node then do a Node clonendash if itrsquos some other kind of Node then do that

clonendash But the Node doesnrsquot know all the other classes

that extend it

bull Reflection can be used to obtain information about a class its members or its methods

CET230 -- Razdan et al 20

Reflection cont

bull The Class class (see javalang) has methods that enable us to get information about the classndash eg getMethod(String name Class

[] parameterTypes) returns ldquoMethodrdquo

bull The Method class (see javalangreflect) has methods that enable us to get information about the Method and even CALL the methodndash Object invoke(Object obj Object[] args)

CET230 -- Razdan et al 21

ldquoBionicrdquo Nodebull We can modify the Node clone as follows

Node nodeClonetry nodeClone = (Node) superclone() catch( CloneNotSupportedException e ) throw new CloneNotSupportedException()if( thisdata instanceof Cloneable ) try Class c = thisdatagetClass() Method m = cgetMethod( clone null )

nodeClonedata = minvoke( thisdata null ) catch( Exception e ) nodeClonedata = thisdata else nodeClonedata = thisdataif( thisnext = null ) nodeClonenext = (Node) thisnextclone()else nodeClonenext = nullreturn( nodeClone )

CET230 -- Razdan et al 22

Revisiting the String classbull Some useful String methods

ndash charAt( int index)

ndash indexOf( char ch )

ndash indexOf( String str )

ndash split( String regex )

ndash startsWith( String prefix )

ndash substring( int beginIndex int endIndex )

ndash toLowerCase()

ndash toUpperCase()

Note StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code It is recommended that anyone seeking this functionality use the split method of String or the javautilregex package instead

CET230 -- Razdan et al 23

Using Files for IObull Using files for IO is similar to standard IObull For standard input you usually use

ndash InputStreamReaderndash BufferedReader

bull For standard output you usually usendash Systemoutprint or println

bull For file input you can usendash FileReaderndash BufferedReader

bull For file output you can usendash FileWriterndash BufferedWriter

CET230 -- Razdan et al 24

FileReader constructorFileReader

public FileReader(String fileName) throws FileNotFoundException

Creates a new FileReader given the name of the file to read from

Parameters fileName - the name of the file to read from

Throws FileNotFoundException - if the named file does not exist is a directory rather than a regular file or for some other reason cannot be opened for reading

CET230 -- Razdan et al 25

Read ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )

String s = inreadLine()int i = 1while( s = null )

Systemoutprintln(ldquoLine ldquo + i + ldquo ldquo + s )

i++s = inreadLine()

inclose()

CET230 -- Razdan et al 26

FileWriter constructor

FileWriter

public FileWriter(String fileName) throws IOException Constructs a FileWriter object given a file name

Parameters fileName - String The system-dependent filename

Throws IOException - if the named file exists but is a directory rather than a regular file does not exist but cannot be created or cannot be opened for any other reason

CET230 -- Razdan et al 27

BufferedWriter

Method Summary void

close() Close the stream

voidflush() Flush the stream

voidnewLine() Write a line separator

voidwrite(char[] cbuf int off int len) Write a portion of an array of characters

voidwrite(int c) Write a single character

voidwrite(String s int off int len) Write a portion of a String

CET230 -- Razdan et al 28

Write ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )BufferedWriter out = new BufferedWriter(

new FileWriter(outfile) )

String s = inreadLine()while( s = null )

outwrite((ssplit(ldquosrdquo))[0])outnewLine()s = inreadLine()

inclose()outclose()

CET230 -- Razdan et al 29

Java Interfaces

bull A Java interface is a set of related methods that a programmer may want to support in a single classndash Eg Cloneablendash Eg Comparablehttpjavasuncomj2se150docsapijavalangComparablehtml

CET230 -- Razdan et al 30

Iterator Pattern

bull Motivation ndash an aggregate object should give you a way to access its

elements without exposing its internal structure

ndash Use of the object may want to traverse the object in many different ways ndash donrsquot want to bloat the interface with may traversal methods even if you could anticipate all the methods needed

ndash May need to have more than one traversal pending on the aggregate at once

CET230 -- Razdan et al 31

Iterator Patternbull Key idea take responsibility for access and

traversal out of the object and put it into an iterator object

bull Iterator provides basic ldquonavigationrdquo methods eg ndash Firstndash Nextndash IsDonendash CurrentItem

CET230 -- Razdan et al 32

Map Interface

bull A map is a collection class in which keyvalue pairs may be added A pair can be retrieved or removed by specifying just its key

CET230 -- Razdan et al 33

TreeMap

bull Javarsquos TreeMapltK Vgt implements the map interface in an efficient way in which the keys are required to come from a class (such as String) that implements the Comparable interface

CET230 -- Razdan et al 34

Example

bull From package javautil

bull TreeMapltString Integergt frequencyData

bull String word

bull Integer count

CET230 -- Razdan et al 35

Operations

bull public V get(K key)

bull public V put(K key V value)

bull public boolean containsKey(K key)

bull public SetltKgt keySet()

bull public int size()

bull public void clear()

CET230 -- Razdan et al 36

Iteration

for (String word wordMapkeySet())

hellipprocess this key which is in variable wordhellip

  • Chapter 5 Generic Programming
  • Javarsquos Object type
  • Issues for ADT that hold objects
  • Widening Conversions
  • Narrowing Conversions
  • Wrapper Classes
  • Old vs New
  • Clones amp Deep Clones
  • Fix (kinda) previous
  • Really fix the shallow clone
  • List clone can use Node clone
  • Doubly Linked List
  • Inheritance
  • Other Lists
  • SkipList example from httpepaperpresscom
  • Abstract Classes
  • Abstract List
  • Implement clone in AbstractList
  • Reflection
  • Reflection cont
  • ldquoBionicrdquo Node
  • Revisiting the String class
  • Using Files for IO
  • FileReader constructor
  • Read Example
  • FileWriter constructor
  • BufferedWriter
  • Write Example
  • Java Interfaces
  • Iterator Pattern
  • Slide 31
  • Map Interface
  • TreeMap
  • Example
  • Operations
  • Iteration
Page 18: Chapter 5 Generic Programming Anshuman Razdan Div of Computing Studies razdan@asu.edu razdan/cst230

CET230 -- Razdan et al 18

Implement clone in AbstractList

bull What Irsquod really like is to implement the clone() in the AbstractList classndash All Lists contain Nodes We donrsquot want to

rewrite the same code for the clone method over and over again in the concrete List classes

ndash Problem what about a DoubleList that contains DoubleNode The AbstractList implementation will not do enoughbecause the Node clone does not do enough

ndash But I WANT it to do enough

CET230 -- Razdan et al 19

Reflectionbull What if we made the Node clone ldquosmarterrdquo

ndash if itrsquos just a Node then do a Node clonendash if itrsquos some other kind of Node then do that

clonendash But the Node doesnrsquot know all the other classes

that extend it

bull Reflection can be used to obtain information about a class its members or its methods

CET230 -- Razdan et al 20

Reflection cont

bull The Class class (see javalang) has methods that enable us to get information about the classndash eg getMethod(String name Class

[] parameterTypes) returns ldquoMethodrdquo

bull The Method class (see javalangreflect) has methods that enable us to get information about the Method and even CALL the methodndash Object invoke(Object obj Object[] args)

CET230 -- Razdan et al 21

ldquoBionicrdquo Nodebull We can modify the Node clone as follows

Node nodeClonetry nodeClone = (Node) superclone() catch( CloneNotSupportedException e ) throw new CloneNotSupportedException()if( thisdata instanceof Cloneable ) try Class c = thisdatagetClass() Method m = cgetMethod( clone null )

nodeClonedata = minvoke( thisdata null ) catch( Exception e ) nodeClonedata = thisdata else nodeClonedata = thisdataif( thisnext = null ) nodeClonenext = (Node) thisnextclone()else nodeClonenext = nullreturn( nodeClone )

CET230 -- Razdan et al 22

Revisiting the String classbull Some useful String methods

ndash charAt( int index)

ndash indexOf( char ch )

ndash indexOf( String str )

ndash split( String regex )

ndash startsWith( String prefix )

ndash substring( int beginIndex int endIndex )

ndash toLowerCase()

ndash toUpperCase()

Note StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code It is recommended that anyone seeking this functionality use the split method of String or the javautilregex package instead

CET230 -- Razdan et al 23

Using Files for IObull Using files for IO is similar to standard IObull For standard input you usually use

ndash InputStreamReaderndash BufferedReader

bull For standard output you usually usendash Systemoutprint or println

bull For file input you can usendash FileReaderndash BufferedReader

bull For file output you can usendash FileWriterndash BufferedWriter

CET230 -- Razdan et al 24

FileReader constructorFileReader

public FileReader(String fileName) throws FileNotFoundException

Creates a new FileReader given the name of the file to read from

Parameters fileName - the name of the file to read from

Throws FileNotFoundException - if the named file does not exist is a directory rather than a regular file or for some other reason cannot be opened for reading

CET230 -- Razdan et al 25

Read ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )

String s = inreadLine()int i = 1while( s = null )

Systemoutprintln(ldquoLine ldquo + i + ldquo ldquo + s )

i++s = inreadLine()

inclose()

CET230 -- Razdan et al 26

FileWriter constructor

FileWriter

public FileWriter(String fileName) throws IOException Constructs a FileWriter object given a file name

Parameters fileName - String The system-dependent filename

Throws IOException - if the named file exists but is a directory rather than a regular file does not exist but cannot be created or cannot be opened for any other reason

CET230 -- Razdan et al 27

BufferedWriter

Method Summary void

close() Close the stream

voidflush() Flush the stream

voidnewLine() Write a line separator

voidwrite(char[] cbuf int off int len) Write a portion of an array of characters

voidwrite(int c) Write a single character

voidwrite(String s int off int len) Write a portion of a String

CET230 -- Razdan et al 28

Write ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )BufferedWriter out = new BufferedWriter(

new FileWriter(outfile) )

String s = inreadLine()while( s = null )

outwrite((ssplit(ldquosrdquo))[0])outnewLine()s = inreadLine()

inclose()outclose()

CET230 -- Razdan et al 29

Java Interfaces

bull A Java interface is a set of related methods that a programmer may want to support in a single classndash Eg Cloneablendash Eg Comparablehttpjavasuncomj2se150docsapijavalangComparablehtml

CET230 -- Razdan et al 30

Iterator Pattern

bull Motivation ndash an aggregate object should give you a way to access its

elements without exposing its internal structure

ndash Use of the object may want to traverse the object in many different ways ndash donrsquot want to bloat the interface with may traversal methods even if you could anticipate all the methods needed

ndash May need to have more than one traversal pending on the aggregate at once

CET230 -- Razdan et al 31

Iterator Patternbull Key idea take responsibility for access and

traversal out of the object and put it into an iterator object

bull Iterator provides basic ldquonavigationrdquo methods eg ndash Firstndash Nextndash IsDonendash CurrentItem

CET230 -- Razdan et al 32

Map Interface

bull A map is a collection class in which keyvalue pairs may be added A pair can be retrieved or removed by specifying just its key

CET230 -- Razdan et al 33

TreeMap

bull Javarsquos TreeMapltK Vgt implements the map interface in an efficient way in which the keys are required to come from a class (such as String) that implements the Comparable interface

CET230 -- Razdan et al 34

Example

bull From package javautil

bull TreeMapltString Integergt frequencyData

bull String word

bull Integer count

CET230 -- Razdan et al 35

Operations

bull public V get(K key)

bull public V put(K key V value)

bull public boolean containsKey(K key)

bull public SetltKgt keySet()

bull public int size()

bull public void clear()

CET230 -- Razdan et al 36

Iteration

for (String word wordMapkeySet())

hellipprocess this key which is in variable wordhellip

  • Chapter 5 Generic Programming
  • Javarsquos Object type
  • Issues for ADT that hold objects
  • Widening Conversions
  • Narrowing Conversions
  • Wrapper Classes
  • Old vs New
  • Clones amp Deep Clones
  • Fix (kinda) previous
  • Really fix the shallow clone
  • List clone can use Node clone
  • Doubly Linked List
  • Inheritance
  • Other Lists
  • SkipList example from httpepaperpresscom
  • Abstract Classes
  • Abstract List
  • Implement clone in AbstractList
  • Reflection
  • Reflection cont
  • ldquoBionicrdquo Node
  • Revisiting the String class
  • Using Files for IO
  • FileReader constructor
  • Read Example
  • FileWriter constructor
  • BufferedWriter
  • Write Example
  • Java Interfaces
  • Iterator Pattern
  • Slide 31
  • Map Interface
  • TreeMap
  • Example
  • Operations
  • Iteration
Page 19: Chapter 5 Generic Programming Anshuman Razdan Div of Computing Studies razdan@asu.edu razdan/cst230

CET230 -- Razdan et al 19

Reflectionbull What if we made the Node clone ldquosmarterrdquo

ndash if itrsquos just a Node then do a Node clonendash if itrsquos some other kind of Node then do that

clonendash But the Node doesnrsquot know all the other classes

that extend it

bull Reflection can be used to obtain information about a class its members or its methods

CET230 -- Razdan et al 20

Reflection cont

bull The Class class (see javalang) has methods that enable us to get information about the classndash eg getMethod(String name Class

[] parameterTypes) returns ldquoMethodrdquo

bull The Method class (see javalangreflect) has methods that enable us to get information about the Method and even CALL the methodndash Object invoke(Object obj Object[] args)

CET230 -- Razdan et al 21

ldquoBionicrdquo Nodebull We can modify the Node clone as follows

Node nodeClonetry nodeClone = (Node) superclone() catch( CloneNotSupportedException e ) throw new CloneNotSupportedException()if( thisdata instanceof Cloneable ) try Class c = thisdatagetClass() Method m = cgetMethod( clone null )

nodeClonedata = minvoke( thisdata null ) catch( Exception e ) nodeClonedata = thisdata else nodeClonedata = thisdataif( thisnext = null ) nodeClonenext = (Node) thisnextclone()else nodeClonenext = nullreturn( nodeClone )

CET230 -- Razdan et al 22

Revisiting the String classbull Some useful String methods

ndash charAt( int index)

ndash indexOf( char ch )

ndash indexOf( String str )

ndash split( String regex )

ndash startsWith( String prefix )

ndash substring( int beginIndex int endIndex )

ndash toLowerCase()

ndash toUpperCase()

Note StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code It is recommended that anyone seeking this functionality use the split method of String or the javautilregex package instead

CET230 -- Razdan et al 23

Using Files for IObull Using files for IO is similar to standard IObull For standard input you usually use

ndash InputStreamReaderndash BufferedReader

bull For standard output you usually usendash Systemoutprint or println

bull For file input you can usendash FileReaderndash BufferedReader

bull For file output you can usendash FileWriterndash BufferedWriter

CET230 -- Razdan et al 24

FileReader constructorFileReader

public FileReader(String fileName) throws FileNotFoundException

Creates a new FileReader given the name of the file to read from

Parameters fileName - the name of the file to read from

Throws FileNotFoundException - if the named file does not exist is a directory rather than a regular file or for some other reason cannot be opened for reading

CET230 -- Razdan et al 25

Read ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )

String s = inreadLine()int i = 1while( s = null )

Systemoutprintln(ldquoLine ldquo + i + ldquo ldquo + s )

i++s = inreadLine()

inclose()

CET230 -- Razdan et al 26

FileWriter constructor

FileWriter

public FileWriter(String fileName) throws IOException Constructs a FileWriter object given a file name

Parameters fileName - String The system-dependent filename

Throws IOException - if the named file exists but is a directory rather than a regular file does not exist but cannot be created or cannot be opened for any other reason

CET230 -- Razdan et al 27

BufferedWriter

Method Summary void

close() Close the stream

voidflush() Flush the stream

voidnewLine() Write a line separator

voidwrite(char[] cbuf int off int len) Write a portion of an array of characters

voidwrite(int c) Write a single character

voidwrite(String s int off int len) Write a portion of a String

CET230 -- Razdan et al 28

Write ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )BufferedWriter out = new BufferedWriter(

new FileWriter(outfile) )

String s = inreadLine()while( s = null )

outwrite((ssplit(ldquosrdquo))[0])outnewLine()s = inreadLine()

inclose()outclose()

CET230 -- Razdan et al 29

Java Interfaces

bull A Java interface is a set of related methods that a programmer may want to support in a single classndash Eg Cloneablendash Eg Comparablehttpjavasuncomj2se150docsapijavalangComparablehtml

CET230 -- Razdan et al 30

Iterator Pattern

bull Motivation ndash an aggregate object should give you a way to access its

elements without exposing its internal structure

ndash Use of the object may want to traverse the object in many different ways ndash donrsquot want to bloat the interface with may traversal methods even if you could anticipate all the methods needed

ndash May need to have more than one traversal pending on the aggregate at once

CET230 -- Razdan et al 31

Iterator Patternbull Key idea take responsibility for access and

traversal out of the object and put it into an iterator object

bull Iterator provides basic ldquonavigationrdquo methods eg ndash Firstndash Nextndash IsDonendash CurrentItem

CET230 -- Razdan et al 32

Map Interface

bull A map is a collection class in which keyvalue pairs may be added A pair can be retrieved or removed by specifying just its key

CET230 -- Razdan et al 33

TreeMap

bull Javarsquos TreeMapltK Vgt implements the map interface in an efficient way in which the keys are required to come from a class (such as String) that implements the Comparable interface

CET230 -- Razdan et al 34

Example

bull From package javautil

bull TreeMapltString Integergt frequencyData

bull String word

bull Integer count

CET230 -- Razdan et al 35

Operations

bull public V get(K key)

bull public V put(K key V value)

bull public boolean containsKey(K key)

bull public SetltKgt keySet()

bull public int size()

bull public void clear()

CET230 -- Razdan et al 36

Iteration

for (String word wordMapkeySet())

hellipprocess this key which is in variable wordhellip

  • Chapter 5 Generic Programming
  • Javarsquos Object type
  • Issues for ADT that hold objects
  • Widening Conversions
  • Narrowing Conversions
  • Wrapper Classes
  • Old vs New
  • Clones amp Deep Clones
  • Fix (kinda) previous
  • Really fix the shallow clone
  • List clone can use Node clone
  • Doubly Linked List
  • Inheritance
  • Other Lists
  • SkipList example from httpepaperpresscom
  • Abstract Classes
  • Abstract List
  • Implement clone in AbstractList
  • Reflection
  • Reflection cont
  • ldquoBionicrdquo Node
  • Revisiting the String class
  • Using Files for IO
  • FileReader constructor
  • Read Example
  • FileWriter constructor
  • BufferedWriter
  • Write Example
  • Java Interfaces
  • Iterator Pattern
  • Slide 31
  • Map Interface
  • TreeMap
  • Example
  • Operations
  • Iteration
Page 20: Chapter 5 Generic Programming Anshuman Razdan Div of Computing Studies razdan@asu.edu razdan/cst230

CET230 -- Razdan et al 20

Reflection cont

bull The Class class (see javalang) has methods that enable us to get information about the classndash eg getMethod(String name Class

[] parameterTypes) returns ldquoMethodrdquo

bull The Method class (see javalangreflect) has methods that enable us to get information about the Method and even CALL the methodndash Object invoke(Object obj Object[] args)

CET230 -- Razdan et al 21

ldquoBionicrdquo Nodebull We can modify the Node clone as follows

Node nodeClonetry nodeClone = (Node) superclone() catch( CloneNotSupportedException e ) throw new CloneNotSupportedException()if( thisdata instanceof Cloneable ) try Class c = thisdatagetClass() Method m = cgetMethod( clone null )

nodeClonedata = minvoke( thisdata null ) catch( Exception e ) nodeClonedata = thisdata else nodeClonedata = thisdataif( thisnext = null ) nodeClonenext = (Node) thisnextclone()else nodeClonenext = nullreturn( nodeClone )

CET230 -- Razdan et al 22

Revisiting the String classbull Some useful String methods

ndash charAt( int index)

ndash indexOf( char ch )

ndash indexOf( String str )

ndash split( String regex )

ndash startsWith( String prefix )

ndash substring( int beginIndex int endIndex )

ndash toLowerCase()

ndash toUpperCase()

Note StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code It is recommended that anyone seeking this functionality use the split method of String or the javautilregex package instead

CET230 -- Razdan et al 23

Using Files for IObull Using files for IO is similar to standard IObull For standard input you usually use

ndash InputStreamReaderndash BufferedReader

bull For standard output you usually usendash Systemoutprint or println

bull For file input you can usendash FileReaderndash BufferedReader

bull For file output you can usendash FileWriterndash BufferedWriter

CET230 -- Razdan et al 24

FileReader constructorFileReader

public FileReader(String fileName) throws FileNotFoundException

Creates a new FileReader given the name of the file to read from

Parameters fileName - the name of the file to read from

Throws FileNotFoundException - if the named file does not exist is a directory rather than a regular file or for some other reason cannot be opened for reading

CET230 -- Razdan et al 25

Read ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )

String s = inreadLine()int i = 1while( s = null )

Systemoutprintln(ldquoLine ldquo + i + ldquo ldquo + s )

i++s = inreadLine()

inclose()

CET230 -- Razdan et al 26

FileWriter constructor

FileWriter

public FileWriter(String fileName) throws IOException Constructs a FileWriter object given a file name

Parameters fileName - String The system-dependent filename

Throws IOException - if the named file exists but is a directory rather than a regular file does not exist but cannot be created or cannot be opened for any other reason

CET230 -- Razdan et al 27

BufferedWriter

Method Summary void

close() Close the stream

voidflush() Flush the stream

voidnewLine() Write a line separator

voidwrite(char[] cbuf int off int len) Write a portion of an array of characters

voidwrite(int c) Write a single character

voidwrite(String s int off int len) Write a portion of a String

CET230 -- Razdan et al 28

Write ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )BufferedWriter out = new BufferedWriter(

new FileWriter(outfile) )

String s = inreadLine()while( s = null )

outwrite((ssplit(ldquosrdquo))[0])outnewLine()s = inreadLine()

inclose()outclose()

CET230 -- Razdan et al 29

Java Interfaces

bull A Java interface is a set of related methods that a programmer may want to support in a single classndash Eg Cloneablendash Eg Comparablehttpjavasuncomj2se150docsapijavalangComparablehtml

CET230 -- Razdan et al 30

Iterator Pattern

bull Motivation ndash an aggregate object should give you a way to access its

elements without exposing its internal structure

ndash Use of the object may want to traverse the object in many different ways ndash donrsquot want to bloat the interface with may traversal methods even if you could anticipate all the methods needed

ndash May need to have more than one traversal pending on the aggregate at once

CET230 -- Razdan et al 31

Iterator Patternbull Key idea take responsibility for access and

traversal out of the object and put it into an iterator object

bull Iterator provides basic ldquonavigationrdquo methods eg ndash Firstndash Nextndash IsDonendash CurrentItem

CET230 -- Razdan et al 32

Map Interface

bull A map is a collection class in which keyvalue pairs may be added A pair can be retrieved or removed by specifying just its key

CET230 -- Razdan et al 33

TreeMap

bull Javarsquos TreeMapltK Vgt implements the map interface in an efficient way in which the keys are required to come from a class (such as String) that implements the Comparable interface

CET230 -- Razdan et al 34

Example

bull From package javautil

bull TreeMapltString Integergt frequencyData

bull String word

bull Integer count

CET230 -- Razdan et al 35

Operations

bull public V get(K key)

bull public V put(K key V value)

bull public boolean containsKey(K key)

bull public SetltKgt keySet()

bull public int size()

bull public void clear()

CET230 -- Razdan et al 36

Iteration

for (String word wordMapkeySet())

hellipprocess this key which is in variable wordhellip

  • Chapter 5 Generic Programming
  • Javarsquos Object type
  • Issues for ADT that hold objects
  • Widening Conversions
  • Narrowing Conversions
  • Wrapper Classes
  • Old vs New
  • Clones amp Deep Clones
  • Fix (kinda) previous
  • Really fix the shallow clone
  • List clone can use Node clone
  • Doubly Linked List
  • Inheritance
  • Other Lists
  • SkipList example from httpepaperpresscom
  • Abstract Classes
  • Abstract List
  • Implement clone in AbstractList
  • Reflection
  • Reflection cont
  • ldquoBionicrdquo Node
  • Revisiting the String class
  • Using Files for IO
  • FileReader constructor
  • Read Example
  • FileWriter constructor
  • BufferedWriter
  • Write Example
  • Java Interfaces
  • Iterator Pattern
  • Slide 31
  • Map Interface
  • TreeMap
  • Example
  • Operations
  • Iteration
Page 21: Chapter 5 Generic Programming Anshuman Razdan Div of Computing Studies razdan@asu.edu razdan/cst230

CET230 -- Razdan et al 21

ldquoBionicrdquo Nodebull We can modify the Node clone as follows

Node nodeClonetry nodeClone = (Node) superclone() catch( CloneNotSupportedException e ) throw new CloneNotSupportedException()if( thisdata instanceof Cloneable ) try Class c = thisdatagetClass() Method m = cgetMethod( clone null )

nodeClonedata = minvoke( thisdata null ) catch( Exception e ) nodeClonedata = thisdata else nodeClonedata = thisdataif( thisnext = null ) nodeClonenext = (Node) thisnextclone()else nodeClonenext = nullreturn( nodeClone )

CET230 -- Razdan et al 22

Revisiting the String classbull Some useful String methods

ndash charAt( int index)

ndash indexOf( char ch )

ndash indexOf( String str )

ndash split( String regex )

ndash startsWith( String prefix )

ndash substring( int beginIndex int endIndex )

ndash toLowerCase()

ndash toUpperCase()

Note StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code It is recommended that anyone seeking this functionality use the split method of String or the javautilregex package instead

CET230 -- Razdan et al 23

Using Files for IObull Using files for IO is similar to standard IObull For standard input you usually use

ndash InputStreamReaderndash BufferedReader

bull For standard output you usually usendash Systemoutprint or println

bull For file input you can usendash FileReaderndash BufferedReader

bull For file output you can usendash FileWriterndash BufferedWriter

CET230 -- Razdan et al 24

FileReader constructorFileReader

public FileReader(String fileName) throws FileNotFoundException

Creates a new FileReader given the name of the file to read from

Parameters fileName - the name of the file to read from

Throws FileNotFoundException - if the named file does not exist is a directory rather than a regular file or for some other reason cannot be opened for reading

CET230 -- Razdan et al 25

Read ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )

String s = inreadLine()int i = 1while( s = null )

Systemoutprintln(ldquoLine ldquo + i + ldquo ldquo + s )

i++s = inreadLine()

inclose()

CET230 -- Razdan et al 26

FileWriter constructor

FileWriter

public FileWriter(String fileName) throws IOException Constructs a FileWriter object given a file name

Parameters fileName - String The system-dependent filename

Throws IOException - if the named file exists but is a directory rather than a regular file does not exist but cannot be created or cannot be opened for any other reason

CET230 -- Razdan et al 27

BufferedWriter

Method Summary void

close() Close the stream

voidflush() Flush the stream

voidnewLine() Write a line separator

voidwrite(char[] cbuf int off int len) Write a portion of an array of characters

voidwrite(int c) Write a single character

voidwrite(String s int off int len) Write a portion of a String

CET230 -- Razdan et al 28

Write ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )BufferedWriter out = new BufferedWriter(

new FileWriter(outfile) )

String s = inreadLine()while( s = null )

outwrite((ssplit(ldquosrdquo))[0])outnewLine()s = inreadLine()

inclose()outclose()

CET230 -- Razdan et al 29

Java Interfaces

bull A Java interface is a set of related methods that a programmer may want to support in a single classndash Eg Cloneablendash Eg Comparablehttpjavasuncomj2se150docsapijavalangComparablehtml

CET230 -- Razdan et al 30

Iterator Pattern

bull Motivation ndash an aggregate object should give you a way to access its

elements without exposing its internal structure

ndash Use of the object may want to traverse the object in many different ways ndash donrsquot want to bloat the interface with may traversal methods even if you could anticipate all the methods needed

ndash May need to have more than one traversal pending on the aggregate at once

CET230 -- Razdan et al 31

Iterator Patternbull Key idea take responsibility for access and

traversal out of the object and put it into an iterator object

bull Iterator provides basic ldquonavigationrdquo methods eg ndash Firstndash Nextndash IsDonendash CurrentItem

CET230 -- Razdan et al 32

Map Interface

bull A map is a collection class in which keyvalue pairs may be added A pair can be retrieved or removed by specifying just its key

CET230 -- Razdan et al 33

TreeMap

bull Javarsquos TreeMapltK Vgt implements the map interface in an efficient way in which the keys are required to come from a class (such as String) that implements the Comparable interface

CET230 -- Razdan et al 34

Example

bull From package javautil

bull TreeMapltString Integergt frequencyData

bull String word

bull Integer count

CET230 -- Razdan et al 35

Operations

bull public V get(K key)

bull public V put(K key V value)

bull public boolean containsKey(K key)

bull public SetltKgt keySet()

bull public int size()

bull public void clear()

CET230 -- Razdan et al 36

Iteration

for (String word wordMapkeySet())

hellipprocess this key which is in variable wordhellip

  • Chapter 5 Generic Programming
  • Javarsquos Object type
  • Issues for ADT that hold objects
  • Widening Conversions
  • Narrowing Conversions
  • Wrapper Classes
  • Old vs New
  • Clones amp Deep Clones
  • Fix (kinda) previous
  • Really fix the shallow clone
  • List clone can use Node clone
  • Doubly Linked List
  • Inheritance
  • Other Lists
  • SkipList example from httpepaperpresscom
  • Abstract Classes
  • Abstract List
  • Implement clone in AbstractList
  • Reflection
  • Reflection cont
  • ldquoBionicrdquo Node
  • Revisiting the String class
  • Using Files for IO
  • FileReader constructor
  • Read Example
  • FileWriter constructor
  • BufferedWriter
  • Write Example
  • Java Interfaces
  • Iterator Pattern
  • Slide 31
  • Map Interface
  • TreeMap
  • Example
  • Operations
  • Iteration
Page 22: Chapter 5 Generic Programming Anshuman Razdan Div of Computing Studies razdan@asu.edu razdan/cst230

CET230 -- Razdan et al 22

Revisiting the String classbull Some useful String methods

ndash charAt( int index)

ndash indexOf( char ch )

ndash indexOf( String str )

ndash split( String regex )

ndash startsWith( String prefix )

ndash substring( int beginIndex int endIndex )

ndash toLowerCase()

ndash toUpperCase()

Note StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code It is recommended that anyone seeking this functionality use the split method of String or the javautilregex package instead

CET230 -- Razdan et al 23

Using Files for IObull Using files for IO is similar to standard IObull For standard input you usually use

ndash InputStreamReaderndash BufferedReader

bull For standard output you usually usendash Systemoutprint or println

bull For file input you can usendash FileReaderndash BufferedReader

bull For file output you can usendash FileWriterndash BufferedWriter

CET230 -- Razdan et al 24

FileReader constructorFileReader

public FileReader(String fileName) throws FileNotFoundException

Creates a new FileReader given the name of the file to read from

Parameters fileName - the name of the file to read from

Throws FileNotFoundException - if the named file does not exist is a directory rather than a regular file or for some other reason cannot be opened for reading

CET230 -- Razdan et al 25

Read ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )

String s = inreadLine()int i = 1while( s = null )

Systemoutprintln(ldquoLine ldquo + i + ldquo ldquo + s )

i++s = inreadLine()

inclose()

CET230 -- Razdan et al 26

FileWriter constructor

FileWriter

public FileWriter(String fileName) throws IOException Constructs a FileWriter object given a file name

Parameters fileName - String The system-dependent filename

Throws IOException - if the named file exists but is a directory rather than a regular file does not exist but cannot be created or cannot be opened for any other reason

CET230 -- Razdan et al 27

BufferedWriter

Method Summary void

close() Close the stream

voidflush() Flush the stream

voidnewLine() Write a line separator

voidwrite(char[] cbuf int off int len) Write a portion of an array of characters

voidwrite(int c) Write a single character

voidwrite(String s int off int len) Write a portion of a String

CET230 -- Razdan et al 28

Write ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )BufferedWriter out = new BufferedWriter(

new FileWriter(outfile) )

String s = inreadLine()while( s = null )

outwrite((ssplit(ldquosrdquo))[0])outnewLine()s = inreadLine()

inclose()outclose()

CET230 -- Razdan et al 29

Java Interfaces

bull A Java interface is a set of related methods that a programmer may want to support in a single classndash Eg Cloneablendash Eg Comparablehttpjavasuncomj2se150docsapijavalangComparablehtml

CET230 -- Razdan et al 30

Iterator Pattern

bull Motivation ndash an aggregate object should give you a way to access its

elements without exposing its internal structure

ndash Use of the object may want to traverse the object in many different ways ndash donrsquot want to bloat the interface with may traversal methods even if you could anticipate all the methods needed

ndash May need to have more than one traversal pending on the aggregate at once

CET230 -- Razdan et al 31

Iterator Patternbull Key idea take responsibility for access and

traversal out of the object and put it into an iterator object

bull Iterator provides basic ldquonavigationrdquo methods eg ndash Firstndash Nextndash IsDonendash CurrentItem

CET230 -- Razdan et al 32

Map Interface

bull A map is a collection class in which keyvalue pairs may be added A pair can be retrieved or removed by specifying just its key

CET230 -- Razdan et al 33

TreeMap

bull Javarsquos TreeMapltK Vgt implements the map interface in an efficient way in which the keys are required to come from a class (such as String) that implements the Comparable interface

CET230 -- Razdan et al 34

Example

bull From package javautil

bull TreeMapltString Integergt frequencyData

bull String word

bull Integer count

CET230 -- Razdan et al 35

Operations

bull public V get(K key)

bull public V put(K key V value)

bull public boolean containsKey(K key)

bull public SetltKgt keySet()

bull public int size()

bull public void clear()

CET230 -- Razdan et al 36

Iteration

for (String word wordMapkeySet())

hellipprocess this key which is in variable wordhellip

  • Chapter 5 Generic Programming
  • Javarsquos Object type
  • Issues for ADT that hold objects
  • Widening Conversions
  • Narrowing Conversions
  • Wrapper Classes
  • Old vs New
  • Clones amp Deep Clones
  • Fix (kinda) previous
  • Really fix the shallow clone
  • List clone can use Node clone
  • Doubly Linked List
  • Inheritance
  • Other Lists
  • SkipList example from httpepaperpresscom
  • Abstract Classes
  • Abstract List
  • Implement clone in AbstractList
  • Reflection
  • Reflection cont
  • ldquoBionicrdquo Node
  • Revisiting the String class
  • Using Files for IO
  • FileReader constructor
  • Read Example
  • FileWriter constructor
  • BufferedWriter
  • Write Example
  • Java Interfaces
  • Iterator Pattern
  • Slide 31
  • Map Interface
  • TreeMap
  • Example
  • Operations
  • Iteration
Page 23: Chapter 5 Generic Programming Anshuman Razdan Div of Computing Studies razdan@asu.edu razdan/cst230

CET230 -- Razdan et al 23

Using Files for IObull Using files for IO is similar to standard IObull For standard input you usually use

ndash InputStreamReaderndash BufferedReader

bull For standard output you usually usendash Systemoutprint or println

bull For file input you can usendash FileReaderndash BufferedReader

bull For file output you can usendash FileWriterndash BufferedWriter

CET230 -- Razdan et al 24

FileReader constructorFileReader

public FileReader(String fileName) throws FileNotFoundException

Creates a new FileReader given the name of the file to read from

Parameters fileName - the name of the file to read from

Throws FileNotFoundException - if the named file does not exist is a directory rather than a regular file or for some other reason cannot be opened for reading

CET230 -- Razdan et al 25

Read ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )

String s = inreadLine()int i = 1while( s = null )

Systemoutprintln(ldquoLine ldquo + i + ldquo ldquo + s )

i++s = inreadLine()

inclose()

CET230 -- Razdan et al 26

FileWriter constructor

FileWriter

public FileWriter(String fileName) throws IOException Constructs a FileWriter object given a file name

Parameters fileName - String The system-dependent filename

Throws IOException - if the named file exists but is a directory rather than a regular file does not exist but cannot be created or cannot be opened for any other reason

CET230 -- Razdan et al 27

BufferedWriter

Method Summary void

close() Close the stream

voidflush() Flush the stream

voidnewLine() Write a line separator

voidwrite(char[] cbuf int off int len) Write a portion of an array of characters

voidwrite(int c) Write a single character

voidwrite(String s int off int len) Write a portion of a String

CET230 -- Razdan et al 28

Write ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )BufferedWriter out = new BufferedWriter(

new FileWriter(outfile) )

String s = inreadLine()while( s = null )

outwrite((ssplit(ldquosrdquo))[0])outnewLine()s = inreadLine()

inclose()outclose()

CET230 -- Razdan et al 29

Java Interfaces

bull A Java interface is a set of related methods that a programmer may want to support in a single classndash Eg Cloneablendash Eg Comparablehttpjavasuncomj2se150docsapijavalangComparablehtml

CET230 -- Razdan et al 30

Iterator Pattern

bull Motivation ndash an aggregate object should give you a way to access its

elements without exposing its internal structure

ndash Use of the object may want to traverse the object in many different ways ndash donrsquot want to bloat the interface with may traversal methods even if you could anticipate all the methods needed

ndash May need to have more than one traversal pending on the aggregate at once

CET230 -- Razdan et al 31

Iterator Patternbull Key idea take responsibility for access and

traversal out of the object and put it into an iterator object

bull Iterator provides basic ldquonavigationrdquo methods eg ndash Firstndash Nextndash IsDonendash CurrentItem

CET230 -- Razdan et al 32

Map Interface

bull A map is a collection class in which keyvalue pairs may be added A pair can be retrieved or removed by specifying just its key

CET230 -- Razdan et al 33

TreeMap

bull Javarsquos TreeMapltK Vgt implements the map interface in an efficient way in which the keys are required to come from a class (such as String) that implements the Comparable interface

CET230 -- Razdan et al 34

Example

bull From package javautil

bull TreeMapltString Integergt frequencyData

bull String word

bull Integer count

CET230 -- Razdan et al 35

Operations

bull public V get(K key)

bull public V put(K key V value)

bull public boolean containsKey(K key)

bull public SetltKgt keySet()

bull public int size()

bull public void clear()

CET230 -- Razdan et al 36

Iteration

for (String word wordMapkeySet())

hellipprocess this key which is in variable wordhellip

  • Chapter 5 Generic Programming
  • Javarsquos Object type
  • Issues for ADT that hold objects
  • Widening Conversions
  • Narrowing Conversions
  • Wrapper Classes
  • Old vs New
  • Clones amp Deep Clones
  • Fix (kinda) previous
  • Really fix the shallow clone
  • List clone can use Node clone
  • Doubly Linked List
  • Inheritance
  • Other Lists
  • SkipList example from httpepaperpresscom
  • Abstract Classes
  • Abstract List
  • Implement clone in AbstractList
  • Reflection
  • Reflection cont
  • ldquoBionicrdquo Node
  • Revisiting the String class
  • Using Files for IO
  • FileReader constructor
  • Read Example
  • FileWriter constructor
  • BufferedWriter
  • Write Example
  • Java Interfaces
  • Iterator Pattern
  • Slide 31
  • Map Interface
  • TreeMap
  • Example
  • Operations
  • Iteration
Page 24: Chapter 5 Generic Programming Anshuman Razdan Div of Computing Studies razdan@asu.edu razdan/cst230

CET230 -- Razdan et al 24

FileReader constructorFileReader

public FileReader(String fileName) throws FileNotFoundException

Creates a new FileReader given the name of the file to read from

Parameters fileName - the name of the file to read from

Throws FileNotFoundException - if the named file does not exist is a directory rather than a regular file or for some other reason cannot be opened for reading

CET230 -- Razdan et al 25

Read ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )

String s = inreadLine()int i = 1while( s = null )

Systemoutprintln(ldquoLine ldquo + i + ldquo ldquo + s )

i++s = inreadLine()

inclose()

CET230 -- Razdan et al 26

FileWriter constructor

FileWriter

public FileWriter(String fileName) throws IOException Constructs a FileWriter object given a file name

Parameters fileName - String The system-dependent filename

Throws IOException - if the named file exists but is a directory rather than a regular file does not exist but cannot be created or cannot be opened for any other reason

CET230 -- Razdan et al 27

BufferedWriter

Method Summary void

close() Close the stream

voidflush() Flush the stream

voidnewLine() Write a line separator

voidwrite(char[] cbuf int off int len) Write a portion of an array of characters

voidwrite(int c) Write a single character

voidwrite(String s int off int len) Write a portion of a String

CET230 -- Razdan et al 28

Write ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )BufferedWriter out = new BufferedWriter(

new FileWriter(outfile) )

String s = inreadLine()while( s = null )

outwrite((ssplit(ldquosrdquo))[0])outnewLine()s = inreadLine()

inclose()outclose()

CET230 -- Razdan et al 29

Java Interfaces

bull A Java interface is a set of related methods that a programmer may want to support in a single classndash Eg Cloneablendash Eg Comparablehttpjavasuncomj2se150docsapijavalangComparablehtml

CET230 -- Razdan et al 30

Iterator Pattern

bull Motivation ndash an aggregate object should give you a way to access its

elements without exposing its internal structure

ndash Use of the object may want to traverse the object in many different ways ndash donrsquot want to bloat the interface with may traversal methods even if you could anticipate all the methods needed

ndash May need to have more than one traversal pending on the aggregate at once

CET230 -- Razdan et al 31

Iterator Patternbull Key idea take responsibility for access and

traversal out of the object and put it into an iterator object

bull Iterator provides basic ldquonavigationrdquo methods eg ndash Firstndash Nextndash IsDonendash CurrentItem

CET230 -- Razdan et al 32

Map Interface

bull A map is a collection class in which keyvalue pairs may be added A pair can be retrieved or removed by specifying just its key

CET230 -- Razdan et al 33

TreeMap

bull Javarsquos TreeMapltK Vgt implements the map interface in an efficient way in which the keys are required to come from a class (such as String) that implements the Comparable interface

CET230 -- Razdan et al 34

Example

bull From package javautil

bull TreeMapltString Integergt frequencyData

bull String word

bull Integer count

CET230 -- Razdan et al 35

Operations

bull public V get(K key)

bull public V put(K key V value)

bull public boolean containsKey(K key)

bull public SetltKgt keySet()

bull public int size()

bull public void clear()

CET230 -- Razdan et al 36

Iteration

for (String word wordMapkeySet())

hellipprocess this key which is in variable wordhellip

  • Chapter 5 Generic Programming
  • Javarsquos Object type
  • Issues for ADT that hold objects
  • Widening Conversions
  • Narrowing Conversions
  • Wrapper Classes
  • Old vs New
  • Clones amp Deep Clones
  • Fix (kinda) previous
  • Really fix the shallow clone
  • List clone can use Node clone
  • Doubly Linked List
  • Inheritance
  • Other Lists
  • SkipList example from httpepaperpresscom
  • Abstract Classes
  • Abstract List
  • Implement clone in AbstractList
  • Reflection
  • Reflection cont
  • ldquoBionicrdquo Node
  • Revisiting the String class
  • Using Files for IO
  • FileReader constructor
  • Read Example
  • FileWriter constructor
  • BufferedWriter
  • Write Example
  • Java Interfaces
  • Iterator Pattern
  • Slide 31
  • Map Interface
  • TreeMap
  • Example
  • Operations
  • Iteration
Page 25: Chapter 5 Generic Programming Anshuman Razdan Div of Computing Studies razdan@asu.edu razdan/cst230

CET230 -- Razdan et al 25

Read ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )

String s = inreadLine()int i = 1while( s = null )

Systemoutprintln(ldquoLine ldquo + i + ldquo ldquo + s )

i++s = inreadLine()

inclose()

CET230 -- Razdan et al 26

FileWriter constructor

FileWriter

public FileWriter(String fileName) throws IOException Constructs a FileWriter object given a file name

Parameters fileName - String The system-dependent filename

Throws IOException - if the named file exists but is a directory rather than a regular file does not exist but cannot be created or cannot be opened for any other reason

CET230 -- Razdan et al 27

BufferedWriter

Method Summary void

close() Close the stream

voidflush() Flush the stream

voidnewLine() Write a line separator

voidwrite(char[] cbuf int off int len) Write a portion of an array of characters

voidwrite(int c) Write a single character

voidwrite(String s int off int len) Write a portion of a String

CET230 -- Razdan et al 28

Write ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )BufferedWriter out = new BufferedWriter(

new FileWriter(outfile) )

String s = inreadLine()while( s = null )

outwrite((ssplit(ldquosrdquo))[0])outnewLine()s = inreadLine()

inclose()outclose()

CET230 -- Razdan et al 29

Java Interfaces

bull A Java interface is a set of related methods that a programmer may want to support in a single classndash Eg Cloneablendash Eg Comparablehttpjavasuncomj2se150docsapijavalangComparablehtml

CET230 -- Razdan et al 30

Iterator Pattern

bull Motivation ndash an aggregate object should give you a way to access its

elements without exposing its internal structure

ndash Use of the object may want to traverse the object in many different ways ndash donrsquot want to bloat the interface with may traversal methods even if you could anticipate all the methods needed

ndash May need to have more than one traversal pending on the aggregate at once

CET230 -- Razdan et al 31

Iterator Patternbull Key idea take responsibility for access and

traversal out of the object and put it into an iterator object

bull Iterator provides basic ldquonavigationrdquo methods eg ndash Firstndash Nextndash IsDonendash CurrentItem

CET230 -- Razdan et al 32

Map Interface

bull A map is a collection class in which keyvalue pairs may be added A pair can be retrieved or removed by specifying just its key

CET230 -- Razdan et al 33

TreeMap

bull Javarsquos TreeMapltK Vgt implements the map interface in an efficient way in which the keys are required to come from a class (such as String) that implements the Comparable interface

CET230 -- Razdan et al 34

Example

bull From package javautil

bull TreeMapltString Integergt frequencyData

bull String word

bull Integer count

CET230 -- Razdan et al 35

Operations

bull public V get(K key)

bull public V put(K key V value)

bull public boolean containsKey(K key)

bull public SetltKgt keySet()

bull public int size()

bull public void clear()

CET230 -- Razdan et al 36

Iteration

for (String word wordMapkeySet())

hellipprocess this key which is in variable wordhellip

  • Chapter 5 Generic Programming
  • Javarsquos Object type
  • Issues for ADT that hold objects
  • Widening Conversions
  • Narrowing Conversions
  • Wrapper Classes
  • Old vs New
  • Clones amp Deep Clones
  • Fix (kinda) previous
  • Really fix the shallow clone
  • List clone can use Node clone
  • Doubly Linked List
  • Inheritance
  • Other Lists
  • SkipList example from httpepaperpresscom
  • Abstract Classes
  • Abstract List
  • Implement clone in AbstractList
  • Reflection
  • Reflection cont
  • ldquoBionicrdquo Node
  • Revisiting the String class
  • Using Files for IO
  • FileReader constructor
  • Read Example
  • FileWriter constructor
  • BufferedWriter
  • Write Example
  • Java Interfaces
  • Iterator Pattern
  • Slide 31
  • Map Interface
  • TreeMap
  • Example
  • Operations
  • Iteration
Page 26: Chapter 5 Generic Programming Anshuman Razdan Div of Computing Studies razdan@asu.edu razdan/cst230

CET230 -- Razdan et al 26

FileWriter constructor

FileWriter

public FileWriter(String fileName) throws IOException Constructs a FileWriter object given a file name

Parameters fileName - String The system-dependent filename

Throws IOException - if the named file exists but is a directory rather than a regular file does not exist but cannot be created or cannot be opened for any other reason

CET230 -- Razdan et al 27

BufferedWriter

Method Summary void

close() Close the stream

voidflush() Flush the stream

voidnewLine() Write a line separator

voidwrite(char[] cbuf int off int len) Write a portion of an array of characters

voidwrite(int c) Write a single character

voidwrite(String s int off int len) Write a portion of a String

CET230 -- Razdan et al 28

Write ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )BufferedWriter out = new BufferedWriter(

new FileWriter(outfile) )

String s = inreadLine()while( s = null )

outwrite((ssplit(ldquosrdquo))[0])outnewLine()s = inreadLine()

inclose()outclose()

CET230 -- Razdan et al 29

Java Interfaces

bull A Java interface is a set of related methods that a programmer may want to support in a single classndash Eg Cloneablendash Eg Comparablehttpjavasuncomj2se150docsapijavalangComparablehtml

CET230 -- Razdan et al 30

Iterator Pattern

bull Motivation ndash an aggregate object should give you a way to access its

elements without exposing its internal structure

ndash Use of the object may want to traverse the object in many different ways ndash donrsquot want to bloat the interface with may traversal methods even if you could anticipate all the methods needed

ndash May need to have more than one traversal pending on the aggregate at once

CET230 -- Razdan et al 31

Iterator Patternbull Key idea take responsibility for access and

traversal out of the object and put it into an iterator object

bull Iterator provides basic ldquonavigationrdquo methods eg ndash Firstndash Nextndash IsDonendash CurrentItem

CET230 -- Razdan et al 32

Map Interface

bull A map is a collection class in which keyvalue pairs may be added A pair can be retrieved or removed by specifying just its key

CET230 -- Razdan et al 33

TreeMap

bull Javarsquos TreeMapltK Vgt implements the map interface in an efficient way in which the keys are required to come from a class (such as String) that implements the Comparable interface

CET230 -- Razdan et al 34

Example

bull From package javautil

bull TreeMapltString Integergt frequencyData

bull String word

bull Integer count

CET230 -- Razdan et al 35

Operations

bull public V get(K key)

bull public V put(K key V value)

bull public boolean containsKey(K key)

bull public SetltKgt keySet()

bull public int size()

bull public void clear()

CET230 -- Razdan et al 36

Iteration

for (String word wordMapkeySet())

hellipprocess this key which is in variable wordhellip

  • Chapter 5 Generic Programming
  • Javarsquos Object type
  • Issues for ADT that hold objects
  • Widening Conversions
  • Narrowing Conversions
  • Wrapper Classes
  • Old vs New
  • Clones amp Deep Clones
  • Fix (kinda) previous
  • Really fix the shallow clone
  • List clone can use Node clone
  • Doubly Linked List
  • Inheritance
  • Other Lists
  • SkipList example from httpepaperpresscom
  • Abstract Classes
  • Abstract List
  • Implement clone in AbstractList
  • Reflection
  • Reflection cont
  • ldquoBionicrdquo Node
  • Revisiting the String class
  • Using Files for IO
  • FileReader constructor
  • Read Example
  • FileWriter constructor
  • BufferedWriter
  • Write Example
  • Java Interfaces
  • Iterator Pattern
  • Slide 31
  • Map Interface
  • TreeMap
  • Example
  • Operations
  • Iteration
Page 27: Chapter 5 Generic Programming Anshuman Razdan Div of Computing Studies razdan@asu.edu razdan/cst230

CET230 -- Razdan et al 27

BufferedWriter

Method Summary void

close() Close the stream

voidflush() Flush the stream

voidnewLine() Write a line separator

voidwrite(char[] cbuf int off int len) Write a portion of an array of characters

voidwrite(int c) Write a single character

voidwrite(String s int off int len) Write a portion of a String

CET230 -- Razdan et al 28

Write ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )BufferedWriter out = new BufferedWriter(

new FileWriter(outfile) )

String s = inreadLine()while( s = null )

outwrite((ssplit(ldquosrdquo))[0])outnewLine()s = inreadLine()

inclose()outclose()

CET230 -- Razdan et al 29

Java Interfaces

bull A Java interface is a set of related methods that a programmer may want to support in a single classndash Eg Cloneablendash Eg Comparablehttpjavasuncomj2se150docsapijavalangComparablehtml

CET230 -- Razdan et al 30

Iterator Pattern

bull Motivation ndash an aggregate object should give you a way to access its

elements without exposing its internal structure

ndash Use of the object may want to traverse the object in many different ways ndash donrsquot want to bloat the interface with may traversal methods even if you could anticipate all the methods needed

ndash May need to have more than one traversal pending on the aggregate at once

CET230 -- Razdan et al 31

Iterator Patternbull Key idea take responsibility for access and

traversal out of the object and put it into an iterator object

bull Iterator provides basic ldquonavigationrdquo methods eg ndash Firstndash Nextndash IsDonendash CurrentItem

CET230 -- Razdan et al 32

Map Interface

bull A map is a collection class in which keyvalue pairs may be added A pair can be retrieved or removed by specifying just its key

CET230 -- Razdan et al 33

TreeMap

bull Javarsquos TreeMapltK Vgt implements the map interface in an efficient way in which the keys are required to come from a class (such as String) that implements the Comparable interface

CET230 -- Razdan et al 34

Example

bull From package javautil

bull TreeMapltString Integergt frequencyData

bull String word

bull Integer count

CET230 -- Razdan et al 35

Operations

bull public V get(K key)

bull public V put(K key V value)

bull public boolean containsKey(K key)

bull public SetltKgt keySet()

bull public int size()

bull public void clear()

CET230 -- Razdan et al 36

Iteration

for (String word wordMapkeySet())

hellipprocess this key which is in variable wordhellip

  • Chapter 5 Generic Programming
  • Javarsquos Object type
  • Issues for ADT that hold objects
  • Widening Conversions
  • Narrowing Conversions
  • Wrapper Classes
  • Old vs New
  • Clones amp Deep Clones
  • Fix (kinda) previous
  • Really fix the shallow clone
  • List clone can use Node clone
  • Doubly Linked List
  • Inheritance
  • Other Lists
  • SkipList example from httpepaperpresscom
  • Abstract Classes
  • Abstract List
  • Implement clone in AbstractList
  • Reflection
  • Reflection cont
  • ldquoBionicrdquo Node
  • Revisiting the String class
  • Using Files for IO
  • FileReader constructor
  • Read Example
  • FileWriter constructor
  • BufferedWriter
  • Write Example
  • Java Interfaces
  • Iterator Pattern
  • Slide 31
  • Map Interface
  • TreeMap
  • Example
  • Operations
  • Iteration
Page 28: Chapter 5 Generic Programming Anshuman Razdan Div of Computing Studies razdan@asu.edu razdan/cst230

CET230 -- Razdan et al 28

Write ExampleBufferedReader in = new BufferedReader(

new FileReader(infile) )BufferedWriter out = new BufferedWriter(

new FileWriter(outfile) )

String s = inreadLine()while( s = null )

outwrite((ssplit(ldquosrdquo))[0])outnewLine()s = inreadLine()

inclose()outclose()

CET230 -- Razdan et al 29

Java Interfaces

bull A Java interface is a set of related methods that a programmer may want to support in a single classndash Eg Cloneablendash Eg Comparablehttpjavasuncomj2se150docsapijavalangComparablehtml

CET230 -- Razdan et al 30

Iterator Pattern

bull Motivation ndash an aggregate object should give you a way to access its

elements without exposing its internal structure

ndash Use of the object may want to traverse the object in many different ways ndash donrsquot want to bloat the interface with may traversal methods even if you could anticipate all the methods needed

ndash May need to have more than one traversal pending on the aggregate at once

CET230 -- Razdan et al 31

Iterator Patternbull Key idea take responsibility for access and

traversal out of the object and put it into an iterator object

bull Iterator provides basic ldquonavigationrdquo methods eg ndash Firstndash Nextndash IsDonendash CurrentItem

CET230 -- Razdan et al 32

Map Interface

bull A map is a collection class in which keyvalue pairs may be added A pair can be retrieved or removed by specifying just its key

CET230 -- Razdan et al 33

TreeMap

bull Javarsquos TreeMapltK Vgt implements the map interface in an efficient way in which the keys are required to come from a class (such as String) that implements the Comparable interface

CET230 -- Razdan et al 34

Example

bull From package javautil

bull TreeMapltString Integergt frequencyData

bull String word

bull Integer count

CET230 -- Razdan et al 35

Operations

bull public V get(K key)

bull public V put(K key V value)

bull public boolean containsKey(K key)

bull public SetltKgt keySet()

bull public int size()

bull public void clear()

CET230 -- Razdan et al 36

Iteration

for (String word wordMapkeySet())

hellipprocess this key which is in variable wordhellip

  • Chapter 5 Generic Programming
  • Javarsquos Object type
  • Issues for ADT that hold objects
  • Widening Conversions
  • Narrowing Conversions
  • Wrapper Classes
  • Old vs New
  • Clones amp Deep Clones
  • Fix (kinda) previous
  • Really fix the shallow clone
  • List clone can use Node clone
  • Doubly Linked List
  • Inheritance
  • Other Lists
  • SkipList example from httpepaperpresscom
  • Abstract Classes
  • Abstract List
  • Implement clone in AbstractList
  • Reflection
  • Reflection cont
  • ldquoBionicrdquo Node
  • Revisiting the String class
  • Using Files for IO
  • FileReader constructor
  • Read Example
  • FileWriter constructor
  • BufferedWriter
  • Write Example
  • Java Interfaces
  • Iterator Pattern
  • Slide 31
  • Map Interface
  • TreeMap
  • Example
  • Operations
  • Iteration
Page 29: Chapter 5 Generic Programming Anshuman Razdan Div of Computing Studies razdan@asu.edu razdan/cst230

CET230 -- Razdan et al 29

Java Interfaces

bull A Java interface is a set of related methods that a programmer may want to support in a single classndash Eg Cloneablendash Eg Comparablehttpjavasuncomj2se150docsapijavalangComparablehtml

CET230 -- Razdan et al 30

Iterator Pattern

bull Motivation ndash an aggregate object should give you a way to access its

elements without exposing its internal structure

ndash Use of the object may want to traverse the object in many different ways ndash donrsquot want to bloat the interface with may traversal methods even if you could anticipate all the methods needed

ndash May need to have more than one traversal pending on the aggregate at once

CET230 -- Razdan et al 31

Iterator Patternbull Key idea take responsibility for access and

traversal out of the object and put it into an iterator object

bull Iterator provides basic ldquonavigationrdquo methods eg ndash Firstndash Nextndash IsDonendash CurrentItem

CET230 -- Razdan et al 32

Map Interface

bull A map is a collection class in which keyvalue pairs may be added A pair can be retrieved or removed by specifying just its key

CET230 -- Razdan et al 33

TreeMap

bull Javarsquos TreeMapltK Vgt implements the map interface in an efficient way in which the keys are required to come from a class (such as String) that implements the Comparable interface

CET230 -- Razdan et al 34

Example

bull From package javautil

bull TreeMapltString Integergt frequencyData

bull String word

bull Integer count

CET230 -- Razdan et al 35

Operations

bull public V get(K key)

bull public V put(K key V value)

bull public boolean containsKey(K key)

bull public SetltKgt keySet()

bull public int size()

bull public void clear()

CET230 -- Razdan et al 36

Iteration

for (String word wordMapkeySet())

hellipprocess this key which is in variable wordhellip

  • Chapter 5 Generic Programming
  • Javarsquos Object type
  • Issues for ADT that hold objects
  • Widening Conversions
  • Narrowing Conversions
  • Wrapper Classes
  • Old vs New
  • Clones amp Deep Clones
  • Fix (kinda) previous
  • Really fix the shallow clone
  • List clone can use Node clone
  • Doubly Linked List
  • Inheritance
  • Other Lists
  • SkipList example from httpepaperpresscom
  • Abstract Classes
  • Abstract List
  • Implement clone in AbstractList
  • Reflection
  • Reflection cont
  • ldquoBionicrdquo Node
  • Revisiting the String class
  • Using Files for IO
  • FileReader constructor
  • Read Example
  • FileWriter constructor
  • BufferedWriter
  • Write Example
  • Java Interfaces
  • Iterator Pattern
  • Slide 31
  • Map Interface
  • TreeMap
  • Example
  • Operations
  • Iteration
Page 30: Chapter 5 Generic Programming Anshuman Razdan Div of Computing Studies razdan@asu.edu razdan/cst230

CET230 -- Razdan et al 30

Iterator Pattern

bull Motivation ndash an aggregate object should give you a way to access its

elements without exposing its internal structure

ndash Use of the object may want to traverse the object in many different ways ndash donrsquot want to bloat the interface with may traversal methods even if you could anticipate all the methods needed

ndash May need to have more than one traversal pending on the aggregate at once

CET230 -- Razdan et al 31

Iterator Patternbull Key idea take responsibility for access and

traversal out of the object and put it into an iterator object

bull Iterator provides basic ldquonavigationrdquo methods eg ndash Firstndash Nextndash IsDonendash CurrentItem

CET230 -- Razdan et al 32

Map Interface

bull A map is a collection class in which keyvalue pairs may be added A pair can be retrieved or removed by specifying just its key

CET230 -- Razdan et al 33

TreeMap

bull Javarsquos TreeMapltK Vgt implements the map interface in an efficient way in which the keys are required to come from a class (such as String) that implements the Comparable interface

CET230 -- Razdan et al 34

Example

bull From package javautil

bull TreeMapltString Integergt frequencyData

bull String word

bull Integer count

CET230 -- Razdan et al 35

Operations

bull public V get(K key)

bull public V put(K key V value)

bull public boolean containsKey(K key)

bull public SetltKgt keySet()

bull public int size()

bull public void clear()

CET230 -- Razdan et al 36

Iteration

for (String word wordMapkeySet())

hellipprocess this key which is in variable wordhellip

  • Chapter 5 Generic Programming
  • Javarsquos Object type
  • Issues for ADT that hold objects
  • Widening Conversions
  • Narrowing Conversions
  • Wrapper Classes
  • Old vs New
  • Clones amp Deep Clones
  • Fix (kinda) previous
  • Really fix the shallow clone
  • List clone can use Node clone
  • Doubly Linked List
  • Inheritance
  • Other Lists
  • SkipList example from httpepaperpresscom
  • Abstract Classes
  • Abstract List
  • Implement clone in AbstractList
  • Reflection
  • Reflection cont
  • ldquoBionicrdquo Node
  • Revisiting the String class
  • Using Files for IO
  • FileReader constructor
  • Read Example
  • FileWriter constructor
  • BufferedWriter
  • Write Example
  • Java Interfaces
  • Iterator Pattern
  • Slide 31
  • Map Interface
  • TreeMap
  • Example
  • Operations
  • Iteration
Page 31: Chapter 5 Generic Programming Anshuman Razdan Div of Computing Studies razdan@asu.edu razdan/cst230

CET230 -- Razdan et al 31

Iterator Patternbull Key idea take responsibility for access and

traversal out of the object and put it into an iterator object

bull Iterator provides basic ldquonavigationrdquo methods eg ndash Firstndash Nextndash IsDonendash CurrentItem

CET230 -- Razdan et al 32

Map Interface

bull A map is a collection class in which keyvalue pairs may be added A pair can be retrieved or removed by specifying just its key

CET230 -- Razdan et al 33

TreeMap

bull Javarsquos TreeMapltK Vgt implements the map interface in an efficient way in which the keys are required to come from a class (such as String) that implements the Comparable interface

CET230 -- Razdan et al 34

Example

bull From package javautil

bull TreeMapltString Integergt frequencyData

bull String word

bull Integer count

CET230 -- Razdan et al 35

Operations

bull public V get(K key)

bull public V put(K key V value)

bull public boolean containsKey(K key)

bull public SetltKgt keySet()

bull public int size()

bull public void clear()

CET230 -- Razdan et al 36

Iteration

for (String word wordMapkeySet())

hellipprocess this key which is in variable wordhellip

  • Chapter 5 Generic Programming
  • Javarsquos Object type
  • Issues for ADT that hold objects
  • Widening Conversions
  • Narrowing Conversions
  • Wrapper Classes
  • Old vs New
  • Clones amp Deep Clones
  • Fix (kinda) previous
  • Really fix the shallow clone
  • List clone can use Node clone
  • Doubly Linked List
  • Inheritance
  • Other Lists
  • SkipList example from httpepaperpresscom
  • Abstract Classes
  • Abstract List
  • Implement clone in AbstractList
  • Reflection
  • Reflection cont
  • ldquoBionicrdquo Node
  • Revisiting the String class
  • Using Files for IO
  • FileReader constructor
  • Read Example
  • FileWriter constructor
  • BufferedWriter
  • Write Example
  • Java Interfaces
  • Iterator Pattern
  • Slide 31
  • Map Interface
  • TreeMap
  • Example
  • Operations
  • Iteration
Page 32: Chapter 5 Generic Programming Anshuman Razdan Div of Computing Studies razdan@asu.edu razdan/cst230

CET230 -- Razdan et al 32

Map Interface

bull A map is a collection class in which keyvalue pairs may be added A pair can be retrieved or removed by specifying just its key

CET230 -- Razdan et al 33

TreeMap

bull Javarsquos TreeMapltK Vgt implements the map interface in an efficient way in which the keys are required to come from a class (such as String) that implements the Comparable interface

CET230 -- Razdan et al 34

Example

bull From package javautil

bull TreeMapltString Integergt frequencyData

bull String word

bull Integer count

CET230 -- Razdan et al 35

Operations

bull public V get(K key)

bull public V put(K key V value)

bull public boolean containsKey(K key)

bull public SetltKgt keySet()

bull public int size()

bull public void clear()

CET230 -- Razdan et al 36

Iteration

for (String word wordMapkeySet())

hellipprocess this key which is in variable wordhellip

  • Chapter 5 Generic Programming
  • Javarsquos Object type
  • Issues for ADT that hold objects
  • Widening Conversions
  • Narrowing Conversions
  • Wrapper Classes
  • Old vs New
  • Clones amp Deep Clones
  • Fix (kinda) previous
  • Really fix the shallow clone
  • List clone can use Node clone
  • Doubly Linked List
  • Inheritance
  • Other Lists
  • SkipList example from httpepaperpresscom
  • Abstract Classes
  • Abstract List
  • Implement clone in AbstractList
  • Reflection
  • Reflection cont
  • ldquoBionicrdquo Node
  • Revisiting the String class
  • Using Files for IO
  • FileReader constructor
  • Read Example
  • FileWriter constructor
  • BufferedWriter
  • Write Example
  • Java Interfaces
  • Iterator Pattern
  • Slide 31
  • Map Interface
  • TreeMap
  • Example
  • Operations
  • Iteration
Page 33: Chapter 5 Generic Programming Anshuman Razdan Div of Computing Studies razdan@asu.edu razdan/cst230

CET230 -- Razdan et al 33

TreeMap

bull Javarsquos TreeMapltK Vgt implements the map interface in an efficient way in which the keys are required to come from a class (such as String) that implements the Comparable interface

CET230 -- Razdan et al 34

Example

bull From package javautil

bull TreeMapltString Integergt frequencyData

bull String word

bull Integer count

CET230 -- Razdan et al 35

Operations

bull public V get(K key)

bull public V put(K key V value)

bull public boolean containsKey(K key)

bull public SetltKgt keySet()

bull public int size()

bull public void clear()

CET230 -- Razdan et al 36

Iteration

for (String word wordMapkeySet())

hellipprocess this key which is in variable wordhellip

  • Chapter 5 Generic Programming
  • Javarsquos Object type
  • Issues for ADT that hold objects
  • Widening Conversions
  • Narrowing Conversions
  • Wrapper Classes
  • Old vs New
  • Clones amp Deep Clones
  • Fix (kinda) previous
  • Really fix the shallow clone
  • List clone can use Node clone
  • Doubly Linked List
  • Inheritance
  • Other Lists
  • SkipList example from httpepaperpresscom
  • Abstract Classes
  • Abstract List
  • Implement clone in AbstractList
  • Reflection
  • Reflection cont
  • ldquoBionicrdquo Node
  • Revisiting the String class
  • Using Files for IO
  • FileReader constructor
  • Read Example
  • FileWriter constructor
  • BufferedWriter
  • Write Example
  • Java Interfaces
  • Iterator Pattern
  • Slide 31
  • Map Interface
  • TreeMap
  • Example
  • Operations
  • Iteration
Page 34: Chapter 5 Generic Programming Anshuman Razdan Div of Computing Studies razdan@asu.edu razdan/cst230

CET230 -- Razdan et al 34

Example

bull From package javautil

bull TreeMapltString Integergt frequencyData

bull String word

bull Integer count

CET230 -- Razdan et al 35

Operations

bull public V get(K key)

bull public V put(K key V value)

bull public boolean containsKey(K key)

bull public SetltKgt keySet()

bull public int size()

bull public void clear()

CET230 -- Razdan et al 36

Iteration

for (String word wordMapkeySet())

hellipprocess this key which is in variable wordhellip

  • Chapter 5 Generic Programming
  • Javarsquos Object type
  • Issues for ADT that hold objects
  • Widening Conversions
  • Narrowing Conversions
  • Wrapper Classes
  • Old vs New
  • Clones amp Deep Clones
  • Fix (kinda) previous
  • Really fix the shallow clone
  • List clone can use Node clone
  • Doubly Linked List
  • Inheritance
  • Other Lists
  • SkipList example from httpepaperpresscom
  • Abstract Classes
  • Abstract List
  • Implement clone in AbstractList
  • Reflection
  • Reflection cont
  • ldquoBionicrdquo Node
  • Revisiting the String class
  • Using Files for IO
  • FileReader constructor
  • Read Example
  • FileWriter constructor
  • BufferedWriter
  • Write Example
  • Java Interfaces
  • Iterator Pattern
  • Slide 31
  • Map Interface
  • TreeMap
  • Example
  • Operations
  • Iteration
Page 35: Chapter 5 Generic Programming Anshuman Razdan Div of Computing Studies razdan@asu.edu razdan/cst230

CET230 -- Razdan et al 35

Operations

bull public V get(K key)

bull public V put(K key V value)

bull public boolean containsKey(K key)

bull public SetltKgt keySet()

bull public int size()

bull public void clear()

CET230 -- Razdan et al 36

Iteration

for (String word wordMapkeySet())

hellipprocess this key which is in variable wordhellip

  • Chapter 5 Generic Programming
  • Javarsquos Object type
  • Issues for ADT that hold objects
  • Widening Conversions
  • Narrowing Conversions
  • Wrapper Classes
  • Old vs New
  • Clones amp Deep Clones
  • Fix (kinda) previous
  • Really fix the shallow clone
  • List clone can use Node clone
  • Doubly Linked List
  • Inheritance
  • Other Lists
  • SkipList example from httpepaperpresscom
  • Abstract Classes
  • Abstract List
  • Implement clone in AbstractList
  • Reflection
  • Reflection cont
  • ldquoBionicrdquo Node
  • Revisiting the String class
  • Using Files for IO
  • FileReader constructor
  • Read Example
  • FileWriter constructor
  • BufferedWriter
  • Write Example
  • Java Interfaces
  • Iterator Pattern
  • Slide 31
  • Map Interface
  • TreeMap
  • Example
  • Operations
  • Iteration
Page 36: Chapter 5 Generic Programming Anshuman Razdan Div of Computing Studies razdan@asu.edu razdan/cst230

CET230 -- Razdan et al 36

Iteration

for (String word wordMapkeySet())

hellipprocess this key which is in variable wordhellip

  • Chapter 5 Generic Programming
  • Javarsquos Object type
  • Issues for ADT that hold objects
  • Widening Conversions
  • Narrowing Conversions
  • Wrapper Classes
  • Old vs New
  • Clones amp Deep Clones
  • Fix (kinda) previous
  • Really fix the shallow clone
  • List clone can use Node clone
  • Doubly Linked List
  • Inheritance
  • Other Lists
  • SkipList example from httpepaperpresscom
  • Abstract Classes
  • Abstract List
  • Implement clone in AbstractList
  • Reflection
  • Reflection cont
  • ldquoBionicrdquo Node
  • Revisiting the String class
  • Using Files for IO
  • FileReader constructor
  • Read Example
  • FileWriter constructor
  • BufferedWriter
  • Write Example
  • Java Interfaces
  • Iterator Pattern
  • Slide 31
  • Map Interface
  • TreeMap
  • Example
  • Operations
  • Iteration