Docsity

Iterators and Design Patterns in Java: Inner Classes, Iterators, and Defensive Copying - P, Study notes of Programming Languages

Partial preview of the text

Download Iterators and Design Patterns in Java: Inner Classes, Iterators, and Defensive Copying - P and more Study notes Programming Languages in PDF only on Docsity!

1

CMSC 433 – Programming Language

Technologies and Paradigms

Spring 2004

Iterators and Design Patterns February 17, 2004

Administrivia

  • Reading, Liskov ch 6, 15
  • Another resource: Thinking in Patterns with Java
    • Link from the class web page
  • Project 2 due February 25
    • Version 3 of code posted

3

Inner Classes

  • Classes can be nested inside other classes
    • These are called inner classes
  • Within a class that contains an inner class, you can use the inner class just like any other class

Example: The Queue Class

class Queue { class Entry { // Java inner class Element elt; Entry next; Entry(Element i) { elt = i; next = null; } } Entry theQueue; void enqueue(Element e) { if (theQueue == null) theQueue = new Entry(e); else { Entry last = theQueue; while (last.next != null) last = last.next; last.next = new Entry(e); } } ...

7

Anonymous Inner Classes

(new Thread() { public void run() { try { Thread.sleep(10006020); System.out.println(”..."); System.exit(1); } catch (Exception e) {} } }).start();**

  • Create anonymous subclass of thread, and invoke method on it

Other Features of Inner Classes

  • Outside of the outer class, use outer.inner notation to refer to type of inner class - E.g., Queue.Entry
  • An inner class marked static does not have a reference to outer class - Can’t refer to instance variables of outer class - Must also use outer.inner notation to refer to inner class
  • Question: Can Queue.Element be made static?

9

Compiling Inner Classes

  • The JVM doesn’t know about inner classes
    • Compiled away, similar to generics
    • Inner class Foo of outer class A produces A$Foo.class
    • Anonymous inner class of outer class A produces A$1.class
  • Why are inner classes useful?

Iteration

  • Goal: Loop through all objects in an aggregate class Node { Element elt; Node next; } Node n = ...; while (n != null) { ...; n = n.next; }
  • Problems:
    • Depends on implementation details
    • Varies from one aggregate to another

13

Using Iterators

Iterator i = c.iterator(); while (i.hasNext()) { Element e = i.next(); // do stuff with e } // alternatively use for for (Iterator i = c.iterator(); i.hasNext(); ) { Element e = (Element) i.next(); // do stuff with e }

Iterators and Queues

  • Recall queue example from beginning of lecture
  • We’ll explore options for adding iterators

15

next() Shouldn’t Mutate Aggregate

class Queue { ... class QueueIterator implements Iterator { Entry rest; QueueIterator(Entry q) { rest = q; } boolean hasNext() { return rest != null; } Element next() throws NoSuchElementException { if (rest == null) throw new NoSuchElementException(); Element e = rest.elt; rest = rest.next; // queue data intact return e; } } }

Evil Mutating Clients

  • But a client could mutate the data structure … HashMap h = ...; ... Iterator i = h.entrySet().iterator(); System.out.println(i.next()); System.out.println(i.next()); h.put(“Foo”, “Bar”); // hash table resize! System.out.println(i.next()); // prints ???

19

Timestamps (cont’d)

... class QueueIterator implements Iterator { int expectedModCount = modCount; // set at iterator // construction time Element next() { if (expectedModCount != modCount) throw new ConcurrentModificationException(); ... } // does hasNext() need to be modified? }}

  • Pro: Iteration construction cheap
  • Con: Doesn’t allow any mutation

Comments

  • Neither solution tracks mutations to container elts
    • Could use clone(), but tricky

21

What if Mutation is Allowed?

  • Allowed mutation must be part of iterator spec public void remove() throws IllegalStateException;
  • Removes from the underlying collection the last element returned by the iterator (optional operation). This method can be called only once per call to next.
  • The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.

Iterators

  • Key ideas
    • Separate aggregate structure from traversal protocol
    • Support additional kinds of traversals
      • E.g., smallest to largest, largest to smallest, unordered
    • Multiple simultaneous traversals
      • Though many Java Collections do not provide this
  • Structure
    • Iterator interface defines traversal protocol
    • Concrete Iterator implementations for each aggregate
      • And for each traversal strategy
    • Aggregate instances create Iterator object instances

25

Object Modeling Technique (OMT)

  • Used to describe patterns in GO4 book
  • Graphical representation of OO relationships
    • Class diagrams show the static relationship between classes
    • Object diagrams represent the state of a program as series of related objects
    • Interaction diagrams illustrate execution of the program as an interaction among related objects

Classes

27

Object instantiation

Subclassing and Abstract Classes

31

Interaction diagrams

time

Structure of Iterator (Cursor) Pattern

33

Components of a Pattern

  • Name(s)
  • Problem
    • Context
    • Real-world example
  • Solution
    • Design/structure
    • Implementation
  • Consequences
  • Variations, known uses

Iterator Pattern, Again

  • Name: Iterator (aka Cursor)
  • Problem:
    • How to process the elements of an aggregate in an implementation-independent manner?
  • Solution:
    • Define an Iterator interface
      • next(), hasNext(), etc. methods
    • Aggregate returns an instance of an implementation of Iterator interface to control the iteration