Presentation is loading. Please wait.

Presentation is loading. Please wait.

Frameworks and Collections Horstmann ch.8-8.4. QUIZ What is the difference between a program library and a framework? 1.There is no difference 2.When.

Similar presentations


Presentation on theme: "Frameworks and Collections Horstmann ch.8-8.4. QUIZ What is the difference between a program library and a framework? 1.There is no difference 2.When."— Presentation transcript:

1 Frameworks and Collections Horstmann ch.8-8.4

2 QUIZ What is the difference between a program library and a framework? 1.There is no difference 2.When using a framework, you extend classes, but when using a program library you construct objects and call methods 3.A framework uses the Hollywood principle ”don’t call us, we call you” (inversion of control) whereas the user maintains control when using a program library 4.A framework consists of multiple classes and uses design patterns, but a program library is a single class defining a set of static methods. 5.I don’t know

3 Frameworks and Collections Frameworks –set of cooperating classes –extending some class –inversion of control –Examples: Applet, graph editor Collections –Use of Collection library classes and services –Extending an abstract class

4 Applets Applet: Java program that runs in a web browser http://www.ventrella.com/Buffon/index.html

5 Applet http://www.cs.au.dk/dProg2/eksempler/forel%e6sninger/frameworks/applet/dprog2Applet.html

6 Example Applet public class dprog2Applet extends Applet { public void init() { try { final Image pic1 = getImage(new URL(getCodeBase(),"image1.jpg")); final Image pic2 = getImage(new URL(getCodeBase(),"image2.jpg")); int delay = Integer.parseInt(getParameter("delay")); timer = new Timer(delay, new ActionListener() { public void actionPerformed(ActionEvent event) { if (image==pic1) image = pic2; else image = pic1; repaint(); } }); } catch (MalformedURLException e) {} } public void start() { timer.start(); } public void stop() { timer.stop(); } public void paint(Graphics g) { if (image != null) g.drawImage(image,0,0,this); } private Timer timer; private Image image; }

7 Applets as a Framework Framework class Applet deals with generic behavior (browser interaction) –Ex: getParameter Programmer extends Applet Inversion of control: framework calls init, start, stop, paint

8 QUIZ don’t call us, we call you Which is an example of inversion of control in a framework? 1.When Collections.sort(…) is executed on an ArrayList 2.When the actionPerformed method in an Actionlistener attached to a JButton is executed 3.When the exception handling code of a try {…} catch (…) {…} is executed 4.I don’t know

9 example: Graph Editor Framework Interactive editing of diagrams Graph consists of nodes and edges Horstman example: UMLEditordProg2 example

10 A Framework Instance defined by user Other classes and interfaces provided by framework

11 Object construction problem? User provides classes implementing Node and extending AbstractEdge Framework needs to generate objects from these, when new nodes/edges are inserted. But classes were not known when coding framework?

12 Solution User provides object (prototype) for each kind of node/edge public Node[] getNodePrototypes() { Node[] nodeTypes = { new CircleNode(Color.BLACK), new CircleNode(Color.WHITE), new SmileyNode(Color.GREEN), new SmileyNode(Color.RED) }; return nodeTypes; } Framework clones prototype object, when new node/edge is inserted Node newNode = (Node) prototype.clone();

13 PROTOTYPE Pattern Context A system instantiates objects of classes that are not known when the system is built. You do not want to require a separate class for each kind of object. You want to avoid a separate hierarchy of classes whose responsibility it is to create the objects. Solution Define a prototype interface type that is common to all created objects. Supply a prototype object for each kind of object that the system creates. Clone the prototype object whenever a new object of the given kind is required.

14 PROTOTYPE Pattern

15 EXAMPLE CircleNode SmileyNode Node GraphPanel

16 QUIZ prototype pattern Consider a client getting an iterator via the listIterator method. Does this exemplify the prototype pattern? 1.Yes, this exemplifies the prototype pattern, since the client does not know the class from which the acquired iterator is an instance 2.No, this does not exemplify the prototype pattern, since the acquired iterator may be created rather than cloned 3.I don’t know

17 Collections Library –standard data structures Classes ArrayList, HashSet, TreeMap, etc –standard services Methods Collections.sort(), etc Framework –Create new data structures Extend abstract classes They work with old services –Create new services Program to interfaces They work with old data structures

18 Collections

19 Collection Interface Collection holds elements in some way Different data structures have different storage strategies Collection interface has methods: boolean add(E obj) boolean addAll(Collection c) void clear() boolean contains(Object obj) boolean containsAll(Collection c) boolean equals(Object obj) int hashCode() boolean isEmpty() Iterator iterator() boolean remove(Object obj) boolean removeAll(Collection c) boolean retainAll(Collection c) int size() Object[] toArray() E[] toArray(E[] a)

20 Iterator Interface Iterator traverses elements of collection boolean hasNext() E next() void remove()

21 Lists Lists are ordered. Several classes implement List interface ArrayList –Random access is efficient LinkedList –Insert/remove an element is efficient get(327) remove()

22 Sets Sets don’t store duplicates Several classes implement Set interface HashSet –equals,hashCode on E used TreeSet –E must implement Comparable Set is tagging interface (no new methods)

23 Maps Map represents a dictionary, i.e. a function from keys (type K ) to values (type V ) Several classes implement Map interface HashMap –equals,hashCode on K used TreeMap –K must implement Comparable Map represents finite set of (key,value) pairs

24 Map & Set Example Map size = new HashMap (); size.put("Aarhus",250000); size.put("Odense",200000); size.put("Aalborg",150000); size.put("Aarhus",300000); Set cities = size.keySet(); System.out.println(cities); System.out.println(size); Initialize map to Aarhus -> 250000 Odense -> 200000 Aalborg -> 150000 Change map entry Aarhus -> 300000 Ask for the domain set of the map {Aarhus, Odense, Aalborg} Prints: [Aarhus, Aalborg, Odense] Prints: [Aarhus=300000, Aalborg=150000, Odense=200000]

25 Services Algorithms –Collections.sort() –Collections.binarySearch() Views –Arrays.asList() Example String[] cities = {"London", "New York", "Aarhus"}; List cityList = Arrays.asList(cities); Collections.sort(cityList); for (int i=0; i< cities.length; i++) System.out.print(cities[i]+" "); Prints: Aarhus London New York

26 QUIZ use of a collection class What change in class Truck is required to make a TreeSet object behave correctly? 1.The redefinition of equals is illegal. It must be removed. 2.The redefinition of equals is legal, but it must be accompanied by a consistent redefinition of hashCode. 3.Redefinition of equals and hashCode are irrelevant, but the class must implement Comparable 4.The class must implement Comparable, and equals, hashCode must be redefined if needed to be consistent with compareTo 5.I don’t know Public class Truck { private String license_no; public boolean equals(Object o) {...} }

27 Creating new Collection class AbstractCollection defines most Collection methods Example of template method in AbstractCollection : public boolean addAll(Collection c) { Iterator it = c.iterator();... for (int i=0; it.hasNext(); i++) add(it.next());... } Only iterator() and size() are left abstract add() throws UnsupportedOperationException –Convenient for immutable collection –Need overriding for mutable collection

28 Priority Queue Contains a (multi)set of elements Operations –Add an element –Remove smallest element Should work with existing Collection classes and services

29 Using a Priority Queue PriorityQueue queue = new PriorityQueue (); Inserting elements queue.add(45); queue.add(23); queue.add(234); queue.add(2); queue.add(23); They can only be extracted smallest first while (queue.size()>0) System.out.print(queue.remove()+" "); Priority Queue works with Collection services Set set = new HashSet (queue); System.out.println(set); 2 23 23 45 234 [2, 234, 23, 45]

30 Specification of Priority Queue class PriorityQueue > extends AbstractCollection { public E remove() {... } public boolean add(E e) {... } public int size() {... } public Iterator iterator() {... } } Priority Queue method Collection methods

31 Implementation of Priority Queue public class PriorityQueue > extends AbstractCollection { //CLASS INVARIANT: elements are sorted in ascending order private List elements = new ArrayList (); public boolean add(E e) { elements.add(e); Collections.sort(elements); return true; } public E remove() { return elements.remove(0); } Very inefficient, but simple

32 Implementation of Priority Queue public int size() { return elements.size(); } public Iterator iterator() { return new Iterator () { public boolean hasNext() { return visited < size(); } public E next() { return elements.get(visited++); } public void remove() { throw new UnsupportedOperationException(); } private int visited = 0; }; }

33 QUIZ extending an abstract collection class The compiler accepts the class Mylist, when I define get(int) and size() methods only. Are the inherited methods iterator() and remove(int) template methods? - Or do they throw UnsupportedOperationException ? Template methodsThrows UnsupportedOperationException 1. iterator(), remove(int) 2. iterator()remove(int) 3. remove(int)iterator() 4. iterator(), remove(int) 5. I don’t know

34 QUIZ What is the difference between a program library and a framework? 1.There is no difference 2.When using a framework, you extend classes, but when using a program library you construct objects and call methods 3.A framework uses the Hollywood principle ”don’t call us, we call you” (inversion of control) whereas the user maintains control when using a program library 4.A framework consists of multiple classes and uses design patterns, but a program library is a single class defining a set of static methods. 5.I don’t know


Download ppt "Frameworks and Collections Horstmann ch.8-8.4. QUIZ What is the difference between a program library and a framework? 1.There is no difference 2.When."

Similar presentations


Ads by Google