lab 7(oop)

Upload: achinthya-perera

Post on 06-Apr-2018

219 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 Lab 7(OOP)

    1/14

    INTRODUCTION

    The Collection Framework provides two general purpose implementations often Set interface, HashSetand TreeSet. More often than not you will use a HashSet for storing your duplicate-free collection. Forefficiency objects added to a HashSet need to implement the hashCode() method in a manner that

    properly distributes the hash codes. While most system classes override the default hashCode()implementation of the Object, when creating your own class to add to a HashSet remember to overridehashCode(). The TreeSet implementations useful when you need to extract elements from a collection ina sorted manner. It is generally faster to add elements to the HasSet then convert the collection to a

    TreeeSet for sorted traversal. To optimize HashSet space usage ,we can tune initial capacity and loadfactor. TreeSet has no tuning options, as the tree is always balanced, ensuring log(n0 performance forinsertions, deletions and queries.

    An iterator visits all elements in a set. A set iterator does not visit the elements in the order in which youinserted them. The set implementation rearranges the elements so that it can locate them quickly.A hash function computes an integer value from an object.A good hash function minimizes collisionsidentical hash codes for different objects.When removing an element from a priority queue, the element with the highest priority is retrieved.A heap is an almost complete tree in which the values of all nodes are at most as large as those oftheirdescendants.The regular layout of a heap makes it possible to store heap nodes efficiently in an array.The heapsort algorithm is based on inserting elements into a heap and removing them in sorted order.

    EXERCISES

    Review Design Patterns

    Singleton

    In software engineering, the singleton pattern is a design pattern used to implement the mathematicalconcept of a singleton, by restricting the instantiation of a class to one object. This is useful whenexactly one object is needed to coordinate actions across the system. The concept is sometimesgeneralized to systems that operate more efficiently when only one object exists, or that restrict theinstantiation to a certain number of objects (say, five). Some consider it an anti-pattern, judging that it isoverused, introduces unnecessary limitations in situations where a sole instance of a class is not actually

    required, and introduces global state into an application.

    http://en.wikipedia.org/wiki/Software_engineeringhttp://en.wikipedia.org/wiki/Design_pattern_(computer_science)http://en.wikipedia.org/wiki/Singleton_(mathematics)http://en.wikipedia.org/wiki/Singleton_(mathematics)http://en.wikipedia.org/wiki/Instantiation_(computer_science)http://en.wikipedia.org/wiki/Object-oriented_programminghttp://en.wikipedia.org/wiki/Anti-patternhttp://en.wikipedia.org/wiki/Global_variableshttp://en.wikipedia.org/wiki/Design_pattern_(computer_science)http://en.wikipedia.org/wiki/Singleton_(mathematics)http://en.wikipedia.org/wiki/Singleton_(mathematics)http://en.wikipedia.org/wiki/Instantiation_(computer_science)http://en.wikipedia.org/wiki/Object-oriented_programminghttp://en.wikipedia.org/wiki/Anti-patternhttp://en.wikipedia.org/wiki/Global_variableshttp://en.wikipedia.org/wiki/Software_engineering
  • 8/3/2019 Lab 7(OOP)

    2/14

    * Singleton Pattern ensure that only one instance of a class is created and Provide a global accesspoint to the object.

    Applicability :Logger Classes

    Configuration Classes

    Accesing resources in shared mode

    Factories implemented as Singletons

    Problems and implementation:Thread-safe implementation for multi-threading use.Lazy instantiation using double locking mechanism.

    Example for Singleton design patternThis example explores how to implement aSingletonPattern on a class in java.The Singleton

    design pattern ensures that only one instance of a class is created, it provides a global point ofaccess to the object and allow multiple instances in the future without affecting a singleton class'sclients. To ensure that only one instance of a class is created we make SingletonPattern asstatic. getInstance() method returns a single instance of the class. We create a private defaultconstructor to avoid outside modification.

  • 8/3/2019 Lab 7(OOP)

    3/14

    publicclassSingleton {privatestaticSingleton instance = newSingleton();privateSingleton() {}publicstaticsynchronizedSingleton getInstance() {returninstance;}publicvoiddoSomething() {for(inti = 0; i < 10; i++) {System.out.println("i = "+ i);}}@OverrideprotectedObject clone() throwsCloneNotSupportedException {thrownewCloneNotSupportedException("Clone is not allowed.");}}

    IteratorIn object-oriented programming, the iterator pattern is adesign patternin which an iteratoris used totraverse acontainerand access the container's elements. The iterator pattern decouplesalgorithmsfromcontainers; in some cases, algorithms are necessarily container-specific and thus cannot be decoupled.

    For example, the hypothetical algorithm SearchForElement can be implemented generally using aspecified type of iterator rather than implementing it as a container-specific algorithm. Thisallows SearchForElement to be used on any container which supports the required type of iterator.

    * Provide a way to access the elements of an aggregate object sequentially withoutexposing its underlying representation.

    Example for Iterator Design Pattern

    http://en.wikipedia.org/wiki/Object-oriented_programminghttp://en.wikipedia.org/wiki/Design_pattern_(computer_science)http://en.wikipedia.org/wiki/Design_pattern_(computer_science)http://en.wikipedia.org/wiki/Iteratorhttp://en.wikipedia.org/wiki/Container_(data_structure)http://en.wikipedia.org/wiki/Container_(data_structure)http://en.wikipedia.org/wiki/Algorithmhttp://en.wikipedia.org/wiki/Algorithmhttp://en.wikipedia.org/wiki/Object-oriented_programminghttp://en.wikipedia.org/wiki/Design_pattern_(computer_science)http://en.wikipedia.org/wiki/Iteratorhttp://en.wikipedia.org/wiki/Container_(data_structure)http://en.wikipedia.org/wiki/Algorithm
  • 8/3/2019 Lab 7(OOP)

    4/14

    The Iterator pattern is one, which allows you to navigate through a collection of data using acommon interface without knowing about the underlying implementation.Iterator should beimplemented as an interface. This allows the user to implement it anyway its easier for him/her toreturn data.

    We use iterators quite frequently in everyday life. For example, remote control of TV. Anyremote control we use, either at home/hotel or at a friends place, we just pick up the TV remote

    control and start pressing Up and Down or Forward and Back keys to iterate through the channels.

    import java.util.ArrayList;

    import java.util.Iterator;

    publicclass IteratorClient {

    publicstaticvoid main (String [] args){

    ArrayList alMarks = new ArrayList();

    alMarks.add(10);

    alMarks.add(20);

    alMarks.add(30);

    Iterator iter = alMarks.iterator();

    while(iter.hasNext())

    {

    System.out.println(iter.next());

    }

    }

    }

    Out put:

    Visitor

    In object-oriented programming and software engineering, the visitordesign pattern is a way ofseparating an algorithm from an object structure on which it operates. A practical result of this

    http://en.wikipedia.org/wiki/Object-oriented_programminghttp://en.wikipedia.org/wiki/Software_engineeringhttp://en.wikipedia.org/wiki/Design_pattern_(computer_science)http://en.wikipedia.org/wiki/Algorithmhttp://en.wikipedia.org/wiki/Object-oriented_programminghttp://en.wikipedia.org/wiki/Software_engineeringhttp://en.wikipedia.org/wiki/Design_pattern_(computer_science)http://en.wikipedia.org/wiki/Algorithm
  • 8/3/2019 Lab 7(OOP)

    5/14

    separation is the ability to add new operations to existing object structures without modifying thosestructures. It is one way to easily follow the open/closed principle.

    In essence, the visitor allows one to add new virtual functions to a family of classes without modifyingthe classes themselves; instead, one creates a visitor class that implements all of the appropriatespecializations of the virtual function. The visitor takes the instance reference as input, and implementsthe goal through double dispatch.

    While powerful, the visitor pattern is more limited than conventional virtual functions. It is not possible

    to create visitors for objects without adding a small callback method inside each class. In naiveimplementations, the callback method in each of the classes is not inheritable.

    Flyweight pattern

    Flyweight is a software design pattern. A flyweight is an object that minimizes memory use by sharingas much data as possible with other similar objects; it is a way to use objects in large numbers when asimple repeated representation would use an unacceptable amount of memory. The term is named afterthe boxing weight class.Often some parts of the object state can be shared and it's common to put themin external data structures and pass them to the flyweight objects temporarily when they are used.

    A classic example usage of the flyweight pattern is the data structures for graphical representation ofcharacters in a word processor. It might be desirable to have, for each character in a document,a glyph object containing its font outline, font metrics, and other formatting data, but this would amountto hundreds or thousands of bytes for each character. Instead, for every character there might bea reference to a flyweight glyph object shared by every instance of the same character in the document;only the position of each character (in the document and/or the page) would need to be stored internally.

    http://en.wikipedia.org/wiki/Open/closed_principlehttp://en.wikipedia.org/wiki/Virtual_functionhttp://en.wikipedia.org/wiki/Double_dispatchhttp://en.wikipedia.org/wiki/Virtual_functionshttp://en.wikipedia.org/wiki/Design_pattern_(computer_science)http://en.wikipedia.org/wiki/Flyweighthttp://en.wikipedia.org/wiki/Word_processorhttp://en.wikipedia.org/wiki/Glyphhttp://en.wikipedia.org/wiki/Reference_(computer_science)http://en.wikipedia.org/wiki/Open/closed_principlehttp://en.wikipedia.org/wiki/Virtual_functionhttp://en.wikipedia.org/wiki/Double_dispatchhttp://en.wikipedia.org/wiki/Virtual_functionshttp://en.wikipedia.org/wiki/Design_pattern_(computer_science)http://en.wikipedia.org/wiki/Flyweighthttp://en.wikipedia.org/wiki/Word_processorhttp://en.wikipedia.org/wiki/Glyphhttp://en.wikipedia.org/wiki/Reference_(computer_science)
  • 8/3/2019 Lab 7(OOP)

    6/14

    Composite

    In software engineering, the composite pattern is a partitioning design pattern. The composite pattern

    describes that a group of objects are to be treated in the same way as a single instance of an object. The

    intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies.

    Implementing the composite pattern lets clients treat individual objects and compositions uniformly.

    http://en.wikipedia.org/wiki/Software_engineeringhttp://en.wikipedia.org/wiki/Design_pattern_(computer_science)http://en.wikipedia.org/wiki/Software_engineeringhttp://en.wikipedia.org/wiki/Design_pattern_(computer_science)
  • 8/3/2019 Lab 7(OOP)

    7/14

    Review Data Structures

    The hashcode calculation was made using the email only, and therefore the equals method was also

    overrided.To implement HashSet and TreeSet the Student class had to implement the Comparable

    interface. Student class was constructed and its objects were input twice in each of the data structures welearnt.For the priority queue to work, MinHeap and PriorityNumber classes were implemented. The

    PriorityNumber object has two parameters; priority and Student object, and the PriorityQueue takes in

    PriorityNumber objects.Finally, the tester class was written to check these codes and the result was

    produced as expected.

    Codes for the Student class:

    publicclass Student implements Comparable{

    private String name;private String email;

    public Student(String aName, String mailAddress){

    name = aName;email = mailAddress;

    }

    public String getDetail(){

    returnname +": "+email;}

    publicboolean equals(Object otherObject){if (otherObject == null) returnfalse;if (getClass() != otherObject.getClass()) returnfalse;Student other = (Student) otherObject;

  • 8/3/2019 Lab 7(OOP)

    8/14

    return email.equals(other.email);}

    publicint hashCode(){int h1 = email.hashCode();finalint HASH_MULTIPLIER = 29;int h = HASH_MULTIPLIER * h1 ;return h;}

    public String toString(){return"Student[name = " + name + ",email=" + email + "]";}publicint compareTo(Object ob){

    Student s = (Student)ob;if (email.equals(s.email)) return 0;elsereturn 1;

    }

    }

    Codes for the MinHeap class:

    import java.util.*;

    publicclass MinHeap{

    public MinHeap(){

    elements = new ArrayList();elements.add(null);}

    publicvoid add(Comparable newElement){

    // Add a new leafelements.add(null);int index = elements.size() - 1;

    // Demote parents that are larger than the new elementwhile (index > 1&& getParent(index).compareTo(newElement) > 0){

    elements.set(index, getParent(index));index = getParentIndex(index);}

    // Store the new element in the vacant slotelements.set(index, newElement);}

    public Comparable peek(){

    returnelements.get(1);}

    public Comparable remove()

  • 8/3/2019 Lab 7(OOP)

    9/14

    {Comparable minimum = elements.get(1);

    // Remove last elementint lastIndex = elements.size() - 1;Comparable last = elements.remove(lastIndex);

    if (lastIndex > 1){

    elements.set(1, last);

    fixHeap();}

    return minimum;}

    privatevoid fixHeap(){Comparable root = elements.get(1);

    int lastIndex = elements.size() - 1;// Promote children of removed root while they are larger than last

    int index = 1;boolean more = true;while (more){

    int childIndex = getLeftChildIndex(index);if (childIndex

  • 8/3/2019 Lab 7(OOP)

    10/14

    publicint size(){

    returnelements.size() - 1;}

    privatestaticint getLeftChildIndex(int index){

    return 2 * index;

    }

    privatestaticint getRightChildIndex(int index){

    return 2 * index + 1;}

    privatestaticint getParentIndex(int index){

    return index / 2;}

    private Comparable getLeftChild(int index){

    returnelements.get(2 * index);}

    private Comparable getRightChild(int index){

    returnelements.get(2 * index + 1);}

    private Comparable getParent(int index){

    returnelements.get(index / 2);}

    private ArrayList elements;}

    Codes for the PriorityNumber class:

    publicclass PriorityNumber implements Comparable{

    privateintpriority;private Student stu;

    public PriorityNumber(int aPriority, Student aStu){priority = aPriority;stu = aStu;}

    public String toString(){return"priority =" + priority + ", Student Detail=" + stu.toString()

    +",Hashcode=" + stu.hashCode();

    }

    publicint compareTo(Object otherObject){PriorityNumber other = (PriorityNumber) otherObject;if (priority < other.priority) return -1;

  • 8/3/2019 Lab 7(OOP)

    11/14

    if (priority > other.priority) return 1;return 0;}}

    Codes For StudentTester class:

    import java.util.ArrayList;import java.util.HashSet;import java.util.LinkedList;import java.util.PriorityQueue;import java.util.TreeSet;

    public class StudentTester {

    public static void main(String[] args) {

    Student a = new Student("john","[email protected]");Student b = new Student("sen","[email protected]");Student c = new Student("clare","[email protected]");Student d = new Student("steve","[email protected]");

    Student e = new Student("creg","[email protected]");Student f = new Student("kushlan","[email protected]");

    System.out.println("hash code of Student a= "+ a.hashCode());

    System.out.println("hash code of Student b= "+ b.hashCode());

    System.out.println("hash code of Student c= "+ c.hashCode());

    System.out.println("hash code of Student d= "+ d.hashCode());

    System.out.println("hash code of Student e= "+ e.hashCode());

    System.out.println("hash code of Student f= "+ f.hashCode());

    ArrayList aList = new ArrayList();System.out.println("\n" + "ArrayList");aList.add(a);aList.add(b);aList.add(c);aList.add(d);aList.add(e);

    aList.add(f);aList.add(a);aList.add(b);aList.add(c);aList.add(d);aList.add(e);aList.add(f);for (Student s : aList)

    System.out.println(s);

    LinkedList lList = new LinkedList();System.out.println("\n" + "LinkedList");lList.add(a);lList.add(b);lList.add(c);

  • 8/3/2019 Lab 7(OOP)

    12/14

    lList.add(d);lList.add(e);lList.add(f);lList.add(a);lList.add(b);lList.add(c);lList.add(d);lList.add(e);lList.add(f);for (Student s : lList)

    System.out.println(s);

    PriorityQueue q = newPriorityQueue();

    System.out.println("\n" + "PriorityQueue");q.add(new PriorityNumber(1, a));q.add(new PriorityNumber(2, b));q.add(new PriorityNumber(3, c));q.add(new PriorityNumber(4, d));q.add(new PriorityNumber(5, e));q.add(new PriorityNumber(6, f));

    q.add(new PriorityNumber(1, a));q.add(new PriorityNumber(2, b));q.add(new PriorityNumber(3, c));q.add(new PriorityNumber(4, d));q.add(new PriorityNumber(5, e));q.add(new PriorityNumber(6, f));while (q.size() > 0)

    System.out.println(q.remove());

    TreeSet t = new TreeSet();System.out.println("\n" + "TreeSet");

    t.add(a);t.add(b);t.add(c);t.add(d);t.add(e);t.add(f);t.add(a);t.add(b);t.add(c);t.add(d);t.add(e);t.add(f);for (Student s : t)

    System.out.println(s);

    HashSet h = new HashSet();System.out.println("\n" + "HashSet");h.add(a);h.add(b);h.add(c);h.add(d);h.add(e);h.add(f);h.add(a);h.add(b);

    h.add(c);h.add(d);h.add(e);h.add(f);for (Student s : h)

    System.out.println(s);

  • 8/3/2019 Lab 7(OOP)

    13/14

    }}

  • 8/3/2019 Lab 7(OOP)

    14/14