Thursday 17 August 2017

GENERIC CLASS TYPE





•A Generic type also referred as a Parameterized type , is  a class or interface type definition that has one or more type parameters. Eg. class Queue <T> { // code Public void enqueue(T item) {//code } } “T” is Type Parameter
•Here the type T can be any class or interface type •BUT WE CAN NOT USE PRIMITIVE TYPE For primitive type we can  use wrapper class..
Example: Queue<Student> s= new Queue<Student> (); Queue<String> str= new Queue<String>(); s.enqueue(new Student()); Str.enqueue(“ABC”);
To create a Queue of int(Primitive type) use INTEGER class
Queue<Integer > q= new Queue<Integer> (); q.enqueue(5) ; // autoboxing
•In java 7 Queue<Student> s= new Queue<Student> (); or Queue<Student> s= new Queue<> ();
Why Type Parameter ??
•We can create a Generic Class using Object class as parameter and return type , but this will not ensure compile time type checking.
•The type  variable we supply is used by compiler to ensure compile-time type safety.
List list= new ArrayList(); list.add("abc"); list.add(new Integer(5)); //OK
Now..
List<String> list1 = new ArrayList<String>(); list1.add("abc"); //list1.add(new Integer(5)); //compiler error
Raw Types
•A raw typeis the name of a generic class or interface without any type arguments. For example, Queue<String> q1 =new Queue<String>(); // Stores only string object
Queue q2 = new Queue(); //stores any object.. Backward compatibility
Runtime Type Of Generic Type Instances
Queue<String> proverbs = new Queue<String>(); Queue<Double> numbers = new Queue<Double>();
SOP("numbers class name " + numbers.getClass().getName()); SOP("proverbs class name " + proverbs.getClass().getName());
SOP("Compare Class objects: " +numbers.getClass().equals(proverbs.getClass()));
o/p Queue Queue true
Multiple Type Parameter
Example: class pair<K, V> { // }
pair<String , integer> p1= new pair();
Type Parameter Bounds
•Single Bound class Queue <T extends A> (Here Bound A can be class or interface)
•Multiple Bound class Queue <T extends A & B & C> (Here the first bound A can be class or interface but B & C can only be class)
Why Type Parameter Bounds??
•When we want to restrict the types that can be used as type arguments in a parameterized type. •If we don’t specify any bounds for a type parameter , it will have type Object as its implicit bound. •For example, if we want that the Generic Queue to be of any Number Type
class Queue<T extends Number> { // } Now we can create Queue of any subtype of Number only..
Queue<Integer> i; Queue<Double> d ; but Queue<String> s; //Error now
Challenge….
•Create a Generic Stack Class
Generic Inteface
•Public intefacelist<E> { void add(E  e); E get() ; }
Using Wildcard (?)
•A wildcard represents any class or interface •Instead of supplying any specific type we can specify argument as a wildcard. •Ex. LinkedList<?> list = new LinkedList<String> ();
•(It work same as creating an objof Object class Object o=new Student())
•Here list can be LinkedListof any class or inteface list=new LinkedList<String>(); or list=new LinkedList<Student>();
•Wildcard as method parameter:
public static void display(LinkedList<?> list) { for(Object o : list) sop(o); }
Constraint on Wildcard
public static void display(LinkedList<? extends Number>         list) { for(Number o : list) sop(o); }
Collection Framework
•A collectionis the term used to describe any object that represents a set of objects grouped together and organized in a particular way in memory. •eg. stack, queue, array , vector etc.
•The java collection Frameworkis a set of generic types that is used to create collection class that support various ways to – Store and Manage  objects of any kind
•Java Collections Framework  is the group of •Collections interfaces •Implementations and •Algorithms (Defined in Collection class)
•Some of the benefits of collections framework are: •Reduced development effort by using core collection classes rather than implementing our own collection classes. •Code quality is enhanced with the use of well tested collections framework classes. •Reusability and Interoperability
•Collections are defined in java.utilpackage
•Using Generic type for collection of objects ensures that one do not inadvertently attempts to store objects of the wrong type.
•Java 1.2 introduced the Collections Framework •Java 5 introduced generics and “generalized” all the existing collections
Types of collection
•Sets Unorderdand unique (No duplicate element) •Sequence (List) Ordered and duplicate element are allowed •Map Pair of object (key and value)
Collections-related Interface hierarchy
Collection
ListSet
SortedSet
Map
SortedMap
Iterator
ListIterator
•The Collectionintefacestores groups of Objects,    with duplicates allowed •The Setinterface extends Collectionbut forbids     duplicates •The Listinterface extends Collection, allows duplicates,    and introduces positional indexing. •Mapis a separate hierarchy
Queue

Collection Interface
// Basic operations intsize(); booleanisEmpty(); booleancontains(Object element); booleanadd(E element);         //optional booleanremove(Object element); //optional Iterator<E> iterator();
// Bulk operations booleancontainsAll(Collection<?> c); booleanaddAll(Collection<? extends E> c); //optional booleanremoveAll(Collection<?> c);        //optional booleanretainAll(Collection<?> c);        //optional void clear();                              //optional
// Array Operations Object[] toArray(); <T> T[] toArray(T[] a);
The Iteratorinterface
•An iterator is an object that will return the elements of a collection, one at a time
•interface Iterator<E>
•booleanhasNext() •Returns true if the iteration has more elements •E next() •Returns the next element in the iteration •void remove() •Removes from the underlying collection the last element returned by the iterator (optional operation)
List IteratorsInterface
•ListIteratoriterfacedeclares methods that traverse a collection of objects backwrdor forwards.
•The ListIteratorinterface extends iteratorinterface. •Methods: •next() •hasNext() •previous() •hasPrevious() •remove() •add()
List Interface
List —an ordered collection (sometimes called a sequence). Lists can contain duplicate elements. The element can be inserted and accessed by their integer index (position) just like an ordinary array.
public interface List<E> extends Collection<E>
E get(intindex); E set(intindex, E element);    booleanadd(E element);         void add(intindex, E element); E remove(intindex);            booleanaddAll(intindex, Collection<? extends E> c);
// Search intindexOf(Object o); intlastIndexOf(Object o);
// Iteration ListIterator<E> listIterator(); ListIterator<E> listIterator(intindex);
// Range-view List<E> subList(intfrom, intto);
Classes implementing List Interface
•Vector<T> •Stack<T> •LinkedList<T> •ArrayList<T>
Vector class
•Like an array, it contains components that can be accessed using an integer index. However, the size of a Vector can grow or shrink as needed to accommodate adding and removing items after the Vector has been created. •Vector is synchronized
•Eg. Vector<String> names = new Vector<String>() ; names.add("sanjay"); names.add("nitu");
ArrayList
•Uses a dynamic array for storing the elements •implements List interface •Same as Vector but ArrayListis not synchronized.
Example of ArrayList
ArrayList<String> arr= new ArrayList<String>() ;
arr.add(“aaa”); arr.add(“bbb”);
Difference between Array and ArrayList
•Arrays can contain primitive or Objects whereas ArrayList can contain only Objects. Arrays are fixed size whereas ArrayListsize is dynamic. Arrays doesn’t provide a lot of features like ArrayList, such as addAll, removeAll, iteratoretc.
Stack Class
•public class Stack<E> extends Vector<E>
•Methods •T push(T obj) •T pop() •T peek(); •intsearch(Object o)
Linked List
•Doubly-linked list implementation of the List
•Additional Methods •addFirst() •addLast() •removeFirst() •removeLast()
Sorting Collection
•sort() of Collections class
ArrayList<String> arr= new ArraList<String>(); arr.add(“sunil”); arr.add(“jatin”); arr.add(“nihal”);
Collections.sort( arr);
Sorting..
•How sorting is done? •Here in previous eamplecompareTo() method of String class is used to compare the two object of collection
•What if the collection is of student object
ArrayList<Student> stud = new ArraList<Student>() // Collections.sort(stud); // ????
Comparable Interface
•To sort any collection object , the class must implement the comparable interfce, and overrides compareTo()
(String  class  implement comparbleand overrides compareTo())
class student implements Comparable { public intcompareTo(){ // code } // other code }
Map Interfce
•Maps are similar to collections but are actually represented by an entirely different class hierarchy. •Maps store objects by key/value pairs •Keys may not be duplicated •Each key may map to only one value
Classes Implementing Map Interface
•HashTable<K,V> (all key ustbe non-null , synchronized )
•HashMap<K,V> (Allow null object and also a key to be null , not synchrnized)
•LinkedHashMap<K,V> (uses doubly-linkelist)
•TreeMap<K,V> (Objects are arranged in ascending order)
Methods of Map Interface
•The two most important methods are: •V put(K key, V value)// adds a key-value pair to the map •V get(Object key)// given a key, looks up the associated value
•Some other important methods are: •Set<K> keySet() •Returns a set view of the keys contained in this map. •Collection<V> values() •Returns a collection view of the values contained in this map
How Hashing is done?
•Hashing is done using the hashCode()method of the key object •Eg •HashMap<String , Person> s= new HashMap();
•Here key is a string object , so hashCode() of String is used
•Note: hashCodemethod is defined in object class so this method is available in all class, many in build classes like String, Integer overrides the hashCode()
Classes implementing Set Interface
•HashSet : •Implementation of a set that uses HashMap •LinkedHashSet: •Implementation of a set using  a hash table with all the entries linked in a doubly linked list •TreeSet: •Implementation of a set that orders the objects in the set in ascending sequence

No comments:

Post a Comment