Sunteți pe pagina 1din 14

INTRODUCTION The Collection Framework provides two general purpose implementations often Set interface, HashSet and TreeSet.

More often than not you will use a HashSet for storing your duplicate-free collection. For efficiency 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 override hashCode(). The TreeSet implementations useful when you need to extract elements from a collection in a 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 load factor. TreeSet has no tuning options, as the tree is always balanced, ensuring log(n0 performance for insertions, deletions and queries. An iterator visits all elements in a set. A set iterator does not visit the elements in the order in which you inserted 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 of theirdescendants. 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 mathematical concept of a singleton, by restricting the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects (say, five). Some consider it an anti-pattern, judging that it is overused, introduces unnecessary limitations in situations where a sole instance of a class is not actually required, and introduces global state into an application.

* Singleton Pattern ensure that only one instance of a class is created and Provide a global access
point 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 pattern This 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 of access to the object and allow multiple instances in the future without affecting a singleton class's clients. To ensure that only one instance of a class is created we make SingletonPattern as static. getInstance() method returns a single instance of the class. We create a private default constructor to avoid outside modification.

public class Singleton { private static Singleton instance = new Singleton(); private Singleton() { } public static synchronized Singleton getInstance() { return instance; } public void doSomething() { for (int i = 0; i < 10; i++) { System.out.println("i = " + i); } } @Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException("Clone is not allowed."); } }

Iterator In object-oriented programming, the iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container's elements. The iterator pattern decouples algorithms from containers; in some cases, algorithms are necessarily container-specific and thus cannot be decoupled. For example, the hypothetical algorithm SearchForElement can be implemented generally using a specified type of iterator rather than implementing it as a container-specific algorithm. This allows 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 without exposing its underlying representation.

Example for Iterator Design Pattern

The Iterator pattern is one, which allows you to navigate through a collection of data using a common interface without knowing about the underlying implementation.Iterator should be implemented as an interface. This allows the user to implement it anyway its easier for him/her to return data. We use iterators quite frequently in everyday life. For example, remote control of TV. Any remote 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; public class IteratorClient { public static void main (String [] args){ ArrayList<Integer> alMarks = new ArrayList<Integer>(); alMarks.add(10); alMarks.add(20); alMarks.add(30); Iterator<Integer> iter = alMarks.iterator(); while(iter.hasNext()) { System.out.println(iter.next()); } } }

Out put:

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

separation is the ability to add new operations to existing object structures without modifying those structures. 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 modifying the classes themselves; instead, one creates a visitor class that implements all of the appropriate specializations of the virtual function. The visitor takes the instance reference as input, and implements the 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 naive implementations, 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 sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory. The term is named after the boxing weight class.Often some parts of the object state can be shared and it's common to put them in 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 of characters 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 amount to hundreds or thousands of bytes for each character. Instead, for every character there might be a 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.

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.

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 we learnt.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:
public class Student implements Comparable{ private String name; private String email; public Student(String aName, String mailAddress) { name = aName; email = mailAddress; } public String getDetail() { return name +": "+email; } public boolean equals(Object otherObject) { if (otherObject == null) return false; if (getClass() != otherObject.getClass()) return false; Student other = (Student) otherObject;

return }

email.equals(other.email);

public int hashCode() { int h1 = email.hashCode(); final int HASH_MULTIPLIER = 29; int h = HASH_MULTIPLIER * h1 ; return h; } public String toString() { return "Student[name = " + name + ",email=" + email + "]"; } public int compareTo(Object ob) { Student s = (Student)ob; if (email.equals(s.email)) return 0; else return 1; } }

Codes for the MinHeap class:


import java.util.*;

public class MinHeap { public MinHeap() { elements = new ArrayList<Comparable>(); elements.add(null); } public void add(Comparable newElement) { // Add a new leaf elements.add(null); int index = elements.size() - 1; // Demote parents that are larger than the new element while (index > 1&& getParent(index).compareTo(newElement) > 0) { elements.set(index, getParent(index)); index = getParentIndex(index); } // Store the new element in the vacant slot elements.set(index, newElement); }

public Comparable peek() { return elements.get(1); }

public Comparable remove()

{ Comparable minimum = elements.get(1); // Remove last element int lastIndex = elements.size() - 1; Comparable last = elements.remove(lastIndex); if (lastIndex > 1) { elements.set(1, last); fixHeap(); } return minimum; } private void 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 = while (more) { int childIndex if (childIndex { // Get smaller true; = getLeftChildIndex(index); <= lastIndex) child

// Get left child first Comparable child = getLeftChild(index); // Use right child instead if it is smaller if (getRightChildIndex(index) <= lastIndex && getRightChild(index).compareTo(child) < 0) { childIndex = getRightChildIndex(index); child = getRightChild(index); } // Check if larger child is smaller than root if (child.compareTo(root) < 0) { // Promote child elements.set(index, child); index = childIndex; } else { // root is smaller than both children more = false; } } else { // No children more = false; } } // Store root element in vacant slot elements.set(index, root); }

public int size() { return elements.size() - 1; }

private static int getLeftChildIndex(int index) { return 2 * index; } private static int getRightChildIndex(int index) { return 2 * index + 1; } private static int getParentIndex(int index) { return index / 2; } private Comparable getLeftChild(int index) { return elements.get(2 * index); } private Comparable getRightChild(int index) { return elements.get(2 * index + 1); } private Comparable getParent(int index) { return elements.get(index / 2); } private ArrayList<Comparable> elements; }

Codes for the PriorityNumber class:


public class PriorityNumber implements Comparable{ private int priority; 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(); } public int compareTo(Object otherObject) { PriorityNumber other = (PriorityNumber) otherObject; if (priority < other.priority) return -1;

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

Codes For StudentTester class:


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

public class StudentTester { public static void main(String[] args) { Student Student Student Student Student Student a b c d e f = = = = = = new new new new new new Student("john","a.aa@x.com"); Student("sen","b.bb@y.com"); Student("clare","c.cc@z.com"); Student("steve","d.dd@z.com"); Student("creg","e.ee@z.com"); Student("kushlan","f.ff@z.com"); of Student a= " of Student b= " of Student c= " of Student d= " of Student e= "

System.out.println("hash code + a.hashCode()); System.out.println("hash code + b.hashCode()); System.out.println("hash code + c.hashCode()); System.out.println("hash code + d.hashCode()); System.out.println("hash code + e.hashCode());

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

ArrayList<Student> aList = new ArrayList<Student>(); 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<Student> lList = new LinkedList<Student>(); System.out.println("\n" + "LinkedList"); lList.add(a); lList.add(b); lList.add(c);

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<PriorityNumber> q = new PriorityQueue<PriorityNumber>(); 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<Student> t = new TreeSet<Student>(); 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<Student> h = new HashSet<Student>(); 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);

} }

CONCLUSION Through this lab session I could learn the applications of designing patterns as well as the basic Object oriented programming concepts. Though This lab session was bit complicated after going through some ULM diagrams I could grab the knowledge and understand the basic. I came across with some difficulties when I write the coding for the Even Iterator. But I could find a similar program from the net. So that I could learn how to make such a program with the current knowledge. Was a very usefull because it again refreshed my memory about design patterns. And how to use them in a example and to get required output. Furthermore I learnt that the inheritance relationships together form a class hierarchy, which helps to organize our programs. In this the Classes whose primary job is to group similar classes is often called an abstract class. I went through Inheritance that define by difference: augment, override, or refine members inherited from superclass as well as the Polymorphism which uses the inheritance to make a relationship. Whenever I met an obstacle to build a program I could reach help from internet to make it a success. REFERENCE C.Horstmanns Big Java, Third Edition (2008, Wiley) http://en.wikipedia.org http://www.ipipan.gda.pl/~marek/objects/TOA/oobasics/oobasics.html wwwseg.cs.hut.fi/tik-76.278/group6/awtpat.html www.industriallogic.com/papers/learning.html www.industriallogic.com/patterns/index.html www.swtech.com/dpattern/ http://www.kodejava.org/examples/12.html http://www.roseindia.net/java/beginners/SingletonPattern.shtm

S-ar putea să vă placă și