COLLECTIONS

JAVA COLLECTIONS

An array is an indexed collection of fixed number of homogeneous type of elements.
The main advantage of array is we can represent multiple values by using a single name so that readability of the code will be improved
Limitations of object type arrays:
i. arrays are fixed in size. i.e once we created an array there is no chance of increasing or decreasing the size based on our requirement. hence to use arrays concept compulsory we should know the size in advance which may not possible always.
ii. Arrays can hold only homogeneous type of elements.
Ex: student[] s=new student[100];
s[0]=new student();
s[1]=new Customer();//CE: incompatible types found: customer required: student
But by using object type array we can represent heterogeneous type of elements
Ex: object[] o=new object[100];
o[0]=new student();
o[1]=new Customer();

iii. Arrays concept is not built based on some data structure. hence readymade method support is not available for Arrays. for every requirement programmer is responsible to write the code.
To overcome the above limitations of arrays we should go for "collections".

i. Collections are growable in nature. i.e based on our requirement we can increase or decrease the size.
ii. by using collection we can represent both homogeneous and heterogeneous type of objects.
iii. every collection class is implemented based on some data structure hence for every requirement ready made method support available so being a programmer we can use those methods directly and we are not responsible to implement logic


Difference between Arrays and Collections:

Arrays
Collections
Fixed in size
Growable in nature
w.r.t memory arrays are not recommended
w.r.t memory collections are recommended
w.r.t performance arrays are recommended
w.r.t performance collections are not recommended
Arrays can hold only homogeneous type of elements
Collections can hold both homo and heterogeneous type of elements
There is no underlying data structure for array hence ready made method support is not available
Every collection class is implemented based on some data structure hence ready-made method support is available for every requirement
Always can hold both primitive and objective
Collections can hold only objects but not primitive


Collection : if we want to represent a group of individual objects as a single entity then we should go for collection.
Collection Framework: it define several classes and interfaces which can be used to represent a group of objects. as a single entity.
Java                                                                  C++
collection ---------------------------------------------container
Collection Framework-------------------------------STL[standard template library]

9 key interfaces of collection framework:
1. Collection
2. List
3. Set
4. Sorted Set
5. Navigable Set
6. Queue
7. Map
8. Sorted Map
9. Navigable Map


1. Collection(i):
if we want to represent a group of individual objects as a single entity then we should go for collection interface.
this interface defines the most common methods. which are applicable for any collection object.
this interface acts as a root interface for entire collection framework 
there is no concrete class which implements collection interface directly.

Package : java.util
Root interface in the collection hierarchy.Some collections allow duplicate elements and others do not. Some are ordered and others unordred. The JDK doesn't provide any direct implementations of this interface: it provides implementations of more specific subinterfaces like Set,List. This interface is typically used to pass collections around and manipulate them where maximum generality is needed.

<E> type of the elements in this collection.
public interface Collection<E> extends Iterable<E>
{
//Query Operatons
int size();//returns number of elements
boolean isEmpty();//returns true if the collection contains no elements
boolean contains(Object o);// returns true if and only if this collection contains at least one element e                                                such that o.equals(e), throws classcasteexception,NullpointerException
Iterator<E> iterator();// returns an iterator over the elements in this collection. Threre are no                                                       guarantee concerning the order in which the elements are returned (unless the                                        collection is an instance that provides the guarantee)
Object[] toArray();  //Returns an array containing all of the elements in this collection

<T> T[] toArrayy(T[] a);//Returns an array containing all of the elements in this collection;
                                         the runtime type of the returned array is that of the specified array


//Modification Operatons

boolean add(E e);//Ensures that this collection contains the specified element (optional
                             operation).  Returns <tt>true</tt> if this collection changed as a
                              result of the call.  (Returns <tt>false</tt> if this collection does
                              not permit duplicates and already contains the specified element.)

boolean remove(E e);//Removes a single instance of the specified element from this
                                        collection, if it is  present

//Bulk Operations
boolean containsAll(Collection<?> c);//Returns <tt>true</tt> if this collection contains all of the                                                                          elements in the specified collection, throws                                                                                              ClassCasteException, NullpointerException
boolean addAll(Collection<? extends E> c);//Adds all of the elements in the specified collection to                                                                            this collection
boolean removeAll(Collection<?> c);//Removes all of this collection's elements that are also                                                                            contained in the specified collection
boolean retainAll(Collection<?> c);//Retains only the elements in this collection that are contained in                                                                    the  specified collection
clear();//removes all the elements in the collection


//Comparision and Hashing

boolean equals(Object o);//Compares the specified object with this collection for equality.
int hashCode();//Returns the hash code value for this collection.

   }

Iterable:Class
package java.lang
import java.util.Iterator;

/*Implementing this interface allows an object to be the target of
 * the "foreach" statement.
 *
 * @param <T> the type of elements returned by the iterator*/
public interface Iterable<T>{
 /**
     * Returns an iterator over a set of elements of type T.
     *
     * @return an Iterator.
     */
    Iterator<T> iterator();
}

Iterator:Interface
package java.util;
/* An iterator over a collection. Iterator takes the place of Enumeration in the Java Collections Framework. Iterators differ from enumerations in two ways:
  • Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
  • Method names have been improved.*/
public interface Iterator<E>{

boolean hasNext();//returns 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 this iterator
}

Collection Vs Collections:
collection is an interface which can be used to represent a group of objects as a single entity where as
collections is a utility class to define several utility methods (sorting, searching) for collection objects.

Collections:Class
/*This class consists exclusively of static methods that operate on or return collections*/
package java.util;
import java.io.serializable;
import java.io.ObjectOutputStream;
import java.io.IOException;
import java.lang.reflect.Array;
public class Collections{
// Suppresses default constructor, ensuring non-instantiability.
    private Collections() {
    }
//Algorithms

/*Tuning parameters for algorithms */
private static final int BINARYSEARCH_THRESHOLD=5000;
.....

/*Sorts the specified list into ascending order
throws ClassCasteException, UnsupportedOperationException,IllegalArgumentException
*/
public static <T extends Comparable<? super T>>  void sort(List<T> list){
Object[] a=list.toArray();
Arrays.sort(a);
ListIterator<T> i=list.listIterator();
for(int j=0;j<a.lenght();j++)
{
i.next();
i.set((T)a[j]);
}
}
/** Sorts the specified list according to the order induced by the specified comparator
throws ClassCasteException, UnsupportedOperationException,IllegalArgumentException
*/
public static <T> void sort(List<T> list, Comparator<? super T> c) {
        Object[] a = list.toArray();
        Arrays.sort(a, (Comparator)c);
        ListIterator i = list.listIterator();
        for (int j=0; j<a.length; j++) {
            i.next();
            i.set(a[j]);
        }
    }

AbstractCollection:
package java.util;
/**
 * This class provides a skeletal implementation of the <tt>Collection</tt>
 * interface, to minimize the effort required to implement this interface. <p>
 **/
public abstract class AbstractCollection<E> implements Collection<E> {
    /**
     * Sole constructor.  (For invocation by subclass constructors, typically
     * implicit.)
     */
    protected AbstractCollection() {
    }
//Query Operations
public abstract Iterator<E> iterator();

    public abstract int size();
 public boolean isEmpty() {
        return size() == 0;
    }

public boolean contains(Object o) {
        Iterator<E> it = iterator();
        if (o==null) {
            while (it.hasNext())
                if (it.next()==null)
                    return true;
        } else {
            while (it.hasNext())
                if (o.equals(it.next()))
                    return true;
        }
        return false;
    }



2. List(I)
it is the child interface of collection. if we want to represent a group of individual objects where duplicates are allowed and insertion order must be preserved then we should go for List(I).

List(i):
package java.util;
/**
 * An ordered collection (also known as a <i>sequence</i>).  The user of this
 * interface has precise control over where in the list each element is
 * inserted.  The user can access elements by their integer index (position in
 * the list), and search for elements in the list.<p>**/
public interface List<E> extends Collection<E>{

//Query operations
size(),isEmpty(),contains(o),iterator(),toArray(),
//Modification Operations
add(), remove(),containsAll(),addAll(),removeAll(),retainAll(),clear()
//Comparision and Hashing
equals(),hashCode(),
//Positional Access Operations
E get(ind index);//
E set(int index, E element);
void add(int index, E element);
E remove(int index);
//Search Operations
int indexOf(Object o);
int lastIndexOf(Object o);

//List iterators
ListIterators<E> listIterator();
ListIterators<E> listIterator(int index);

//view
List<E> subList(int fromIndex, int toIndex);
}

ArrayList:

public class ArrayList<E> extends AbstractList<E>,implements List<E>,RandomAccess,Cloneable,java.io.Serializable
{
//Default capacity=10
implementatikon of methods;
}




[vector,stack are considered as legacy classes]
Note: Vector and Stack classes are re engineered in 1.2 version. to fit in collection framework by implementing List interface.

3. Set(I);
it is the child interface of collection. if we want to represent a group of individual objects. where duplicates are not allowed and insertion order is not preserved then we should go for Set
                                     Collection(I)[1.2]
                                           |
                                           |
                                      Set(I)[1.2]
                                           |
                                           |
                                       HashSet(I)[1.2]
                                             |
                                             |
                                           LinkedHashSet[1.4]

4. Sorted Set(I):
it is the child interface of set. if we want to represent a group of individual objects without duplicate according to some sorting order. then we should go for sorted list.

5. NavigableSet(I);
 it is the child interface of sorted set . it defines several methods for navigation purpose.
                             Collection(I)[1.2]
                                    | 
                                    |
                               Set(I)[1.2]
                                     |
                                     |
                               SortedSet(I)[1.2]
                                      |
                                      |
                                NavigableSet(I)[1.6]
                                       ^
                                        |
                                        |
                                    TreeSet[1.2]
6. Queue:
it is the child interface of collection . if we want to represent a group of individual objects. prior to processing then we should go for queue.
   
Note: All the above interfaces[collection,List, Set, SortedSet, NavigableSet, Queue] meant for representing individual objects.
if we want to represent [key, value] pairs then we should go for Map[interface]

7.Map:
if we want to represent a group of objects as [key,value] pair. then we should go for Map interface.
it is not child interface of collection.
duplicate keys are not allowed but values can be duplicated
8. SortedMap:
it is the child interface of Map. if we want to represent a group of objects as [key,value] pairs. According to some sorting order of keys. then we should go for sorted Map.

9. Navigable map:
it is the child interface of sorted map. this interface provides several methods for navigation purposes.

            Map(I)[1.2]
               |
               |
               SortedMap(I)[1.2]
                |
                |
             NavigableMap(I)[1.6]
              |
              |
          TreeMap[1.2]


Utility Classes: Collections, Arrays, 
Cursors: Enumerators[1.0], Iterator, ListIterator
The following are the legacy characters in collection framework
i. Enumerator(I)
ii. Dictionary(AC)
iii. Vector(C)
iv. Stack(C)
v. HashTable(C)
vi. Properties

i Collection:
if we want to present a group of individual objects as a single entity. then we should go for collection interface.
collection interface defines the most common methods which are applicable for any collection object.
collection(I) define the following methods.
public Abstract boolean add(object o)
public Abstract boolean addAll(Collection c)
public Abstract boolean remove(object o)
public Abstract boolean removeAll(Collection c)
public Abstract boolean retainAll(collection c)
public Abstract void clear()
public Abstract boolean contains(Object o)
public Abstract boolean containsAll(Collection c)
public Abstract boolean isEmpty()
public Abstract int size()
public Abstract object[] toArray[]
public Abstract Iterator iterator()

public interface java.util.Collection<E extends java.lang.Iterable> extends java.lang.object implements java.lang.Iterable<E>

java.lang.Iterable contains iterator() method.

ii.List(I):
 it is the child interface of collection. if we want to represent a group of individual objects where duplicates are allowed and insertion order must be preserved then we should go for list.
we can defferentiate duplicate objects and preserve insertion order by using index. hence plays very important role in List
list interface defines the following specific methods
 boolean add(int index, object o)
boolean addAll(int index, Collection c)
Object get(int index)
Object remove(int index)
object set(int index, object new)
 to represent the element present at specified index with provided object and returns old object
int indexOf(Object o)
  returns index of first occurance of Object 'O'
int lastIndexOf(Object o)
ListIterator listIterator()


a. ArrayList
the underlying datastructure is ResizableArray/GrowableArray
insertion order must be preserved, duplicate objects are allowed.
Null insertion is possible
heterogeneous objects are allowed(heterogeneous objects are allowed in everywhere except TreeSet and TreeMap)
Constructor:
i. ArrayList l=new ArrayList();
creates an arraylist object with default initial capacity 10. once ArrayList reaches its max capacity then a new ArrayList object will be created with newcapacity=(currentcapacity*(3/2))+1
ii. ArrayList l=new ArrayList(int InitialCapacity);
creates an empty ArrayList object with specified initial capacity
iii. ArrayList l=new ArrayList(Collection c)
creates an equivalent ArrayList object for the given collection object. this constructore means for inter convention between collection objects
Ex: import java.util.*
class ArrayListDemo{
p s v main(String args[])
{
 ArrayList l=new ArrayList();
l.add("A");
l.add(10);
l.add("A");
l.add(null);
sop(l);
l.remove(2);
sop(l);
l.add(2,"M");
l.add("N");
sop(l);
}
}
o/p: [A,10,A,null]
[A,10,null]
[A,10,M,null,N]

usually we can use collections to hold and transfer Data to provide support for this requirement. Every collection class implement serializable and clonable interface.
ArrayList and vector classes implements RandomAccess interface. so that we can access any random element whit the same speed.

ArrayList l1=new ArrayList();
linkedList l2=new LinkedList();
sop(l1 instanceof serializable)//true
sop(l2 instanceof cloneable);//true
sop(l1 instanceof RandomAccess)//true
sop(l2 instanceof RandomAccess);//false
ArrayList is teh worst choice if we want to perform insert / remove in the middle . because if insertion at particular every element moves one place forward opposite for remove so time taking.

Difference between ArrayList & Vector:
ArrayList
Vector
No method in AL is synchronized
Every method in vector class is synchronized
Multiple threads can operate simultaneously and hence ArrayList object is not thread safe
At a time one thread is allowed to operate on vector object and hence vector is thread safe
Threads are not required to wait and hence relatively performance is high
With the increasing waiting time of thread hence performance is low
It is non-legacy and introduced in 1.2v
It is legacy and introduced in 1.0 version.

how to get Synchronized Version of ArrayList Object:
by default ArrayList is non-synchronized but we can get synchronized version of ArrayList object by using synchronizedList() method of Collections class.
public static List synchronizedList(List l)

Ex: ArrayList l=new ArrayList();
List l1=Collections.synchronizedList(l);
here l1 is synchronized version
l is non-synchronized version
similaryly we can get synchronized version of Set & Map objects. by using the following methods of collections class
public static Set synchronizedSet(Set s)
public Static Map synchronizedMap(Map m)

LinkedList:
the underlying Data structure is double linked list
heterogeneous objects are allowed
duplicate objects are allowed
null insertion possible
Implement serializable and cloneable interfaces but not RandomAccess
Best choice if our frequest operation insertion/deletion in the middle. Worst if our frequest operation is retrieval operation.
usually we can use Linked List for implementing stacks and queues to provide support for this requirement LinkedList class defines the following 6 methods
void addFirst(Object o)
void addLast(Object o)
Object getFirst()
Object getLast()
Object removeFirst()
Object removeLast()

Constructors:
LinkedList l=new LinkedList();
creates an empty linked list object
LinkedList l=new LinkedList(Collection c)
creates an equivalent linked list object for the given collection object
Ex: import java.uti.*
class LinkedListDemo
{
p s v main(-){
LinkedList l=new LinkedList();
l.add("durga");
l.add(30);
l.add(null);l.add("durga");l.set(0,"software");l.set(0,"venki");
l.removeLast();
l.addFirst("CCC");
sop(l);
}
}
o/p: [CCC,Venki,Software,30,null]

Vector:
the underlying datastructure is Resizable Array or growable Array
duplicates are allowed insertion order will be preserved
heterogeneous objects are allowed. 'null' insertion is possible
implements serializable & cloneable and RandomAccess interfaces
Everymethod is synchronized and hence vector object is ThreadSafe
Best choise for retrieval operations
Worst choise if our frequent operation is insertion /deletion in the middle.
Constructors:
  Vector v=new Vector()
creates and empty vector object with default initial capacity '10' once vector reaches its max capacity a new vector object will be created with double capacity
newcapacity=currentcapacity*2;
Vector v=new Vector(int initialcapacity)
creates an empty vector object with the specified initial capacity
Vector v-=new Vector(int initialcapacity,int incrementalcapacity)
Vector v=new Vector(Collection c)
Methods:
to add objects:
add(Object o)--Collection
add(int indexed,Object o)---list
addElement(Object o)--Vector

For removing objects:
remove(Object o)--Collection
removeElement(Object o)-_Vector
remove(int index)--list
removElementAt(int index)--vector
clear()---collection
removeAllElements()--Vector

For Accessing Elements:
Object get(int index)--list
Object elementAt(int index)--vector
Object firstElement()--Vector
Object lastElement()--Vector

other methods:
int size()
returns the number of elements present in vector
int capacity()
returns the total number of elements that a vector can accommodate
Enumeration elements()

Ex: import java.util.*;
class VectorDemo
{
p s v main(-)
{
  vector v=new Vector(10,3);
sop(v.capacity());
for(int i=0;i<=10;i++)
v.addElement(i);
sop(v.capacity());
v.addElemetn("A");
sop(v.capacity());
sop(V);
}
}
o/p: 10
10
13
[0,1,2,3,4,5,6,7,8,9,10]


Stack:
stack is the child class of vector
it is a specially designed class for last in Frist out(LIFO) order.
Constructors:
stack s=new stack();
methods:
object push(Object o)
to insert an object into the stack
Object pop()
to remove and return top of the stack
Object peek()
to return top of the stack without removal
boolean empty()
returns true if stack is empty
int search(Object o)
returns offset if the element is available otherwise returns '-1'
offset is the number of element from the top in the stack
Ex: import java.util.*;
class StackDemo{
Stack s=new Stack();
s.push("A");
s.push("B");
s.push("C");
sop(s);//[A,B,C] out of [C ,B,A] because here insertion order must be preserved
sop(s.search("A"));
sop(s.search("Z"));
}
}
| __C___ |1
|___B___|2
|____A__|3

o/p: [A,B,C]
3
-1

The 3 Cursors of JAVA:
if we want to get objects one by one from the collection then we should go for cursors.
there are 3 types of cursors available in java
1. Enumeration
2. Iteratior
3. ListIterator

1. Enumeration:
we can use Enumeration to get objects one by one from legacy collection objects
we can create Enumeration object by using elements() method
public Enumeration element();
Ex: Enumeration e=v.element();
here v is vector object
Enumeration(I) interface defines the following two methods
i. public boolean hasMoreElements()
ii.public object nextElement()
Ex: import java.util.*;
class EnumerationDemo{
public class void main(-)
{
Vector v=new Vector();
for(int i=0;i<=10;i++)
v.addElement(i)
sop(v);
Enumerator e=v.elements();
while(e.hasMoreElements()){
Integer i=(Integer)e.nextElement();
if(i%2==0)
sop(i);
}
sop(v);
}
o/p: [0,1,2,3,4,5,6,7,8,9,10]
0
2
4
6
8
10
[0,1,2,3,4,5,6,7,8,9,10]
limitations of Enumeraton:
Enumeration concept is Applicable only for legacy classes and it is not a universal cursor
by using enumeration we can perform only read operation and we can't perform remove operations
to overcome the aboce limitations we should go for iterator


Iterator:
We can apply iterator concept for any type of collection object and hence it is a universal cursor. by using iterator we can perform both read and remove operations.
we can create iterator object by using iterator() method of collection interface
public Iterator iterator()
Ex: Iterator itr=c.iterator()
c is any collection object
methods:
public boolean hasNext()
public Object next()
public void remove()
Ex: import java.util.*;
class IteratorDemo{
p s v main(-){
ArrayList al=new ArrayList();
for(int i=0;i<=10;i++)
al.add(i);
sop(al);
Iterator itr=al.iterator();
while(itr.hasNext()){
Integer i=(Integer)itr.next();

if(i%2==0)
sop(i);
else
itr.remove();
}
sop(l);
}
}
o/p:
 [0,1,2,3,4,5,6,7,8,9,10]
0
2
4
6
8
10
 [0,2,4,6,8,10]

limitations of Iterator:
by using Enumeration and iterator. we can always move only towards forward direction i.e these one one direction cursors(forward direction)
By using iteration we can perform only read and remove operations and we can't perform replacement and addition of new objects.
to overcome the aboce limitations we should go for ListIterator

ListIterator:
List iterator is a bidirectional cursor and hence we can move either to the forward or to the backward direction
by using ListIterator we can perform replacement and adddition of new objects in addition to read and remove operations.
ListIterator(I) is the child interface of Iterator(I)
we can create ListIterator object by using ListIterator() method present in List(I) interface
Iterator(I)
^
|
ListIterator(I)

public ListIterator listIterator()
ListIterator ltr=l.listIterator()
here 'l' is List object
method of ListIterator:
ListIterator defines the following '9' methods
//forward
public boolean hasNext()
public object next()
public int nextIndex()


//Backward
public boolean hasPrevious()
public Object previous()
public int previousIndex()

public void remove()
public void set(OBject new)
public void add(Object new) //adds beside curent object

Ex: import java.util.*
class ListIteratorDemo{
p s v main(-){
LinkedList l=new LinkedList();
l.add("balakrishna");
l.add("venki");
l.add("chiru");
l.add("nag");
sop(l);
ListIterator ltr=l.listIterator();
while(ltr.hasnext()){
String s=(String)ltr.next();
if(s.equals("venki")){
ltr.remove("nag");
}
if(s.equals("nag")){
ltr.add("chaitu");
}
if(s.equsl("chiru"))
ltr.add("Charan");
sop(l);
}
}
o/p:


Note: the most powerful cursor is ListIterator but its limitation is it is applicable only for List objects.

Comparision of all Java cursors:
Property
Enumeraton
Iterator
ListIterator
Is it legacy
Yes
No
No
Applicable
Only for legacy classes
Any collection object
Only for list objects
Movement
Single direction(only forward)
Single direction(only forward)
Bidirections(forward and backward)
How to get it
Using elements() method
Using iterator() method
By using listIterator() method
Accessibility
Only read
Read and remove
Remove,add, replace and read
Methods
hasMoreElements()
nextElement()
hasNext()
next()
remove()
9 methods
Set:
It is the child interface of collection
If we want to represent a group of individual objects where duplicates are not allowed and insertion order is not preserved then we should go for “Set”
Collection(I)

FIG:

Set interface doesn’t contain any new methods we have to use only Collection interface methods.
HashSet:
The underlying datastructure for HashSet is HashTable
Duplicates are not allowed
Insertion order is not preserved and it is based on hashcode of the objects.
Heterogeneous objects are allowed
Null insertion is possible
hashSet implements serializable and cloneable interfaces
Constructors:
HashSet h=new hashSet();
Creates an empty hashSet object with default initial capacity 16 and default fill ration 0.75 i.e 75%
HashSet h=new HashSet(int initialCapacity)
Creates an empty hashset object with the specified initial capacity and default fill ration 0.75
HashSet h=new hashSet(int initialcapacity, float fillRatio)
HashSet h=new HashSet(Collection c)
Ex: import java.util.*;
Class hashSetDemo
{
P s v main(-){
HashSet h=new HashSet();
h.add(“B”);
h.add(“C”);
h.add(“D”);
h.add(“Z”);
h.add(null);
h.add(10);
sop(h.add(“Z”));//flase
sop(h);
}
}
o/p: false
[null,D,B,C,10,Z]
Note: duplicates are not allowed in the set if we are trying to insert duplicate objects we won’t get any compiletime or runtime error add(-) method simply returns false
LinkedHashSet:
It is the child class of HashSet
It is exactly same as HashSet except the following differences
HashSet
LinkedHashSet
The underlying data structure is HashTable
The underlying data structure is a combination of HashTable and Linked List
Insertion order is not preserved
Insertion order is preserved
Introduced in 1.2v
Introduced in 1.4v

in the above example if we replace HashSet with LinkedHashSet the following is the output
o/p: false
[B,C,D,Z,null,10]
i.e insertion order is preserved
Note: usually we can use Linked HashSet for Ram,cache implementing code. Applications where duplicates are not allowed but insertion order must be preserved
SortedSet:
It is the child interface of set.
If we want to represent a group of unique objects. According to some sorting order then we should go for sortedset
The sorting order can be either natural sorting order or customized sorting order
Sortedset interface defines the following 6 methods
Object first() returns first element of sortedset
Object last() returns last element of sorted set
Sortedset headset(Object obj)
Returns sortedset whose elements are less thant (<)obj
Sortedset tailset(Object obje)
Returns sorted set whose eleements are (>=obje)
Sortedset  subset(Object obj1,Object obj2)
Returns sortedset whose elements >=obj1 & <obj2
Comparator comparator()

Returns comparator object that describes the underlying sorting technique if we are using default natural sorting order then this method returns ‘null’
Ex:









First()—100
Last()—107
headset(102)---[100,101]
tailSet(102)—[102,104,107,110]
subset(102,107)—[102,104]
comparator—null
TreeSet:
The underlying datastructure is Balanced Tree
Duplicates are not allowed
Insertion order is not preserved and it is based on sorting order
Heterogeneous objects are not allowed by mistake if we are trying to insert heterogeneous objects we will get RuntimeException saying “ClassCasteException”
Null insertion is possible but only once
Constructors:
TreeSet t=new TreeSet();
Creates an empty Treeset object where sorting order is default natural sorting order
Treeset t=new TreeSet(comparator c)
Creates an empty TreeSet object where the sorting order is customized sorting order
TreeSet t=new TreeSet(SortedSet c)
TreeSet t=new TreeSet(Collection c)
Ex: import java.util.*
Class treesetdemo{
P s v main(-){
Treeset t=new TreeSet();
t.add(“A”);
t.add(“a”);
t.add(“B”);
t.add(“Z”);
t.add(“L”);
//t.add(new Integer(10));//CE:ClassCasteexception
//t.add(null);CE: NullpointerException
Sop(t);
}
}
o/p: [A,B,L,Z,a]
ànull Acceptance
For the non-empty TreeSet if we are trying to insert null then we will get Nullpointerexception
For the empty treeset as the first element null insertion is possible but after inserting if we are tyring to insert any other element we will get ‘NullPointerexception”
Ex: import java.util.*
Class TreeSetDemo{
P s v main(-){
TreeSet t=new treeSet();
t.add(new StringBugger(“A”));
t.add(new StringBugger(“Z”));
t.add(new StringBugger(“L”));
t.add(new StringBugger(“B”));
sop(t);
}}
Error : here StringBuffer not implements comparable but string implements comparable
o/p: java.lang.ClassCasteException
Note: if we are depending on default natural sorting order compulsory objects should be homogeneous and comparable otherwise we will get ClassCasteException
An object is said to be comparable iff the corresponding class implements comparable interface
String class and all wrapper classes implements comparable interface not StringBuffer class doesn’t implement comparable interface
Comparable Interface:
Comparable interface present in java.lang package and contains only one method compareTo()
Public int compareTo(Object obj)
Ex: obje1.compareTo(obje2)
       Returns ‘-ve’ iff obje1 has to come before obj2
       Returns ‘+ve’ iff obje1 has to come after obje2
       Returns ‘0’ iff obje1 & obje2 are equal

Ex: sop(“A”.compareTo(“Z”));/-ve
Sop(“Z”.compareTo(“A”));/+Ve
Sop(“A”.compareTo(“A”));//0
Sop(“A”.compareTo(null));//RE: NullPointerException
Sop(“A”.compareTo(new Integer(10));//RE: ClassCasteException

If we are depending on default natural sorting order internally JVM will use compareTo(-) method to arrange objects in sorting order
Note: if we are not satisfied with default natural sorting order or if default sorting order is not available then we can define our sorting by using comparator
Comparable meant for default natural sorting order where as comparator meant for customized sorting order
Comparator:
Comparator interface present in java.uti.package and it contains two methods
i.                     Public int compare(object obj1,object obj2)
Returns –ve iff obj1 has to come before obj2
Returns +ve iff obj2 has to come after obj2
Returns 0 iff obj1 and obj2 are equal
ii.                   Public Boolean equals(object obj)
wherever we are implementing comparator we have to provide implementation compulsory for compare method.
Implementing equals(-) method is optional because it is already inheriting from object class through inheritance
Ex: TreeSet t=new TreeSet(new comparator())
t.add(10);
t.add(0);---+veàcompare(0,10)
t.add(15)----‘-ve’àcompare(15,10)
t.add(5)---+ve-àcompare(5,15)
                  +veàcompare(5,10)
                    -ve-àcompare(5,0)
t.add(20)-- +veàcompare(20,15)
t.add(20)—0àcompare(20,20)
sop(t);[20,15,10,5,0]
àimport java.util.*;
Class ComparatorDemo{
P s v main(-){
TreeSet t=new TreeSet(new myComparator());--LINE 1
t.add(10);
t.add(0);
t.add(15);
t.add(5);
t.add(20);
t.add(20);
sop(t);
}
}
Class mycomparator implements Comparator{
Public int compare(Object o1, Object o2)
{
Integer i1=(Integer)o1;
Integer i2=(Integer)o2;
If(i1<i2)
Return +1;
Else if(i1>i2)
Return -1;
Else
Return 0;
}
}
o/p:[20,15,10,0]
At LINE1 if we are not passing comparator object then JVM will call compareTo(-) method which is for default natural sorting in this case the output is [0,5,10,15,20]
At LINE 1 if we are passing comparator object then JVM will call compare(_) method while arranging elements, which is meant for customized sorting order.
Hence in this caset the output is[20,15,10,0]
àVarious Possible implementations of Compare Method:
Public clas myComparator implements comparator{
Public int compare(object o1,object o2)
{
Integer i1=(Integer) o1;
Integer i2=(Integer) o2;
//return i1.compareTo(i2);[0,5,10,15,20]
//return –i1.compareTo(i2);[20,15,10,5,0]
//return i2.compareTo(i1); ;[20,15,10,5,0]
//return –i2.compareTo(i1);// [0,5,10,15,20]
//returns -1; ;[20,15,10,5,0][reverse of insertion]
//return +1; [0,5,10,15,20]insertion order
//return 0;[10]

è Write a program to String objects into the TreeSet where the sorting order is reverse of alphabetical order
Import java.util.*;
Class TreeSetDemo
{
P s v main(-){
TreeSet t=new TreeSet(new myComparator());
t.add(“Roja”);
t.add(“Shobarani”);
t.add(“Rajakumari”);
t.add(“GangaBhavani”);
t.add(“Ramulamma”);
sop(t);
}
}
Class myComparator implements Comparator{
Public int compare(Object o1,Object o2)
{
String s1=o1.toString();
String s2=o2.toString();
             Return s2.compare(s1);
//return –s1.compareTo(s2);
}
}
o/p: [shobarani,Rajakumari,Ramulamma,Roja,GangaBhavani]
àwrite a program to insert StringBuffer objects into the TreeSet where the Sorting order is alphabetical order
Import java.util.*;
Class TreeSetDemo{
P s v main(-)
{
TreeSet t=new TreeSet(new myComparator);
t.add(new StringBugger(“A”));
t.add(new StringBugger(“Z”));
t.add(new StringBugger(“K”));
t.add(new StringBugger(“L”));
sop(t);
}
}
Class myComparator implements comparator{
Public int compare(Object o1, Object o2)
{
String s1=o1.toString();//convert String buffer to String
String s2=o2.toString();
Returns s1.compareTo(s2);
}
}
àwrite a program to insert String and StringBugger objects into the TreeSet where the sorting order is increasing length order .if two objects are having the same length then consider them alphabetical order
Import java.util.*;
Class treeSetDemo{
P s v main(-){
TreeSet t=new treeSet(new myComparator());
t.add(“A”);
t.add(new StringBugger(“ACC”))’
t.add(new StringBugger(“AA”));
t.add(“XX”);
t.add(“ABCD”);
t.add(“A”);
}
}
Class myComparator implements comparator
{
Public int compare(Object o1, Object o2)
{
String s1=o1.toString();
String s2=o2.toString();
Int l1=s1.length();
Int l2=s2.length();
If(l1<l2)
Return -1;
Else if(l1>l2)
Return +1;
Else
Return s1.compareTo(s2);
}
}
[A,AA,XX,ABC,ABCD]
Note: if we are depending on default natural sorting order compulsory the objects should be homogeneous and comparable otherwise we will get runtime exception saying classCasteException
If we are defining our own soring by comparator then our object need not be comparable and homoheneous.
àcompare vs Comparator
·         for predefined comparable classes default natural sorting order is already available if we are not satisfied with default natural sorting order we can define our own sorting by comparator object
·         for predefined non comparable classes default natural sorting order is not already available hence we can define our own sorting by comparator object
·         for our own classes like employee we can define natural sorting order by implementing comparable interface. The person who is using our class if he is not satisfied with natural sorting order he can define his own sorting byusing comparator
·         à write a program to sort employee records based on their eid’s and their names use natural sorting(for eids) and csustom sorting for(names)
Import java.util.*;
Class Employee implements Comparable{
String name;
Int eid;
Employee(String name,int eid)
{
This.name=name;
This.eid=eid;
}
Public String toString()
{
return name+”__”+eid;
}
Public int compareTo(Object obj)//natural sorting order
{
Int eid1=this.eid;
Employee e=(Employee)obj1;
Int eid2=e.eid;
If(eid1<eid2)
Return -1;
If(eid1>eid2)
Return +1;
Else
Return 0;
}
}
Class compcomp{
Pu s v main(-)
{
Employee e1=new Employee(“nag”,100);
Employee e2=new Employee(“balaiah”,200);
Employee e3=new Employee(“chiru”,50);



Employee e2=new Employee(“venki”,150);
Employee e2=new Employee(“nag”,100);

TreeSet t=new TreeSet();
t.add(e1);
t.add(e2); t.add(e3);
t.add(e4);
t.add(e5);
sop(t);
TreeSet t=new TreeSet(new myComparator())

TreeSet t=new TreeSet();
t.add(e1);
t.add(e2); t.add(e3);
t.add(e4);
t.add(e5);
sop(t);

}
}
Class myComparator implements Comparator{
Public int compare(Object obj1,Object obj2)
{
Employee e1=(Employee)obj1;
Employee e2=(Employee)obj2;
String s1=e1.name;
String s2=e2.name;
Returns s1.compareTo(s2);
}
}
o/p: [chiru-50,nag-100,venki-150,balaiah-200]
[balaiah-200,chiru-50,nag-100,venki-150]
àdifference between Comparable and comparator

Comparable
Comparator
It is meant for default natural sorting order
It is meant for customized sorting order
Present in java.lang package
Present in java.util package
Contains only one method compareTo()
Contains two mentods
Copare()
Equals()
All wrapperclasses and String class implements comparable interface
Only one predefined class implements comparator interface
i.e collector(java.text.*)





àcomparision of Set implements classes:
Property
HashSet
LinkedHashSet
TreeSet
Underlying data structure
HashTable
HashTable + LinkedList
Balanced Tree
Insertion order
Not preserved
Preserved
Not preserved
Sorting order
Not applicable
Not applicable
Applicable
Heterogeneous objects
Allowed
Allowed
Not allowed(by default)
If we define our own sorting allowed
Null insertion
Allowed
Allowed
For empty tree set as first element allowed
Duplicate objects
Not allowed
Not allowed
Not allowed

Map:
Fig

If we want to represent a group of objects as (key,value) pairs then we should go for Map.
Map is not a child interface of collection
Both key and value are objects
Duplicate keys are not allowed and values can be duplicated
Each(key,value) pair is called one “entry”
Key
Value
101(object)
Sal(object)
102
Raj
103
App
104
Div
Entry

Methods of Map Interface:
Object put(Object key,Object value)
To insert one(key,value) pair  to the Map. If the specified key is already available then the old value will be replaced with new vvalue and old value will be returned
Void putAll(Map m)
To insert a group of key,value paris to the Map
Object get(Object key)
It returns the value associated with specified key.
If the key is not associated then we will get null
Object remove(Object key)
To remove the entry associated with specified key and return the corresponding value
Boolean containsKey(Object key)
Boolean containsValue(Object value)
Boolean isEmpty()
Int size()
Void clear()
//Collection views of Map
Set keyset()
Collection values()
Set entrySet()
Entry Interface:
Each key,value pair is called entry without existing Map object there is no chance of existing entry object hence interface entry is defined inside Map interface
Interface Map{
Interface Entry{
Object getKey();
Object getValue():
Object setValue(Object obj);
}
}

HashMap:
Underlying data structure is hashTable duplicate keys are not allowed but values can be duplicated
Insertion order is not preserved and it is based on hashCode of the keys
Heterogenous objects are allowed for both key,values
Null key is allowed (only once) and null values are allowed (any number)
àdifference between HashMap and Hashtable
HashMap
HashTable
No method present in HashMap is synchronized
Every method present in Hashtable is synchronized
hashMap object is not thread safe
Hashtable object is Thread Safe
Relatively performance is high
Relatively performance is low
Null is allowed for boht key,values
Null is not allowed for keys, and values otherwise we will get RuntimeException saying NullPointerException
It is non-legacy and introduced in 1.2v
It is legacy and introduced in 1.0 v

Note: by default hashMap object is not synchronized but we can get synchronized version of HashMap by using synchronized Map(-) method of collections class
Constructor:
HashMap m=new HashMap();
Creates an empty HashMap object with default initial capacity ‘16’ and default fill ration 0.74
HashMap h=new HashMap(int initialCapacity)
HashMap h=new HashMap(int initialCapacity, float fillration)
HashMap h=new HashMap(Map m)
Internal conversion for Map object
Ex: import java.util.*
Class hashMapDemo
{
P s v main(-){
hashMap h=new HashMap();
m.put(“chiranjeevit”,700);
m.put(“balaiah”,800);
m.put(“venkatesh”,200);
m.put(“nagarjuna”,500);
sop(m);
sop(m.put(“chiranjeevit”,100));
Set s=m.keySet();
Sop(s);
Collection c=m.values();
Sop©;
Set s1=m.entrySet();
Sop(s1);
Iterator itr=s1.iterator();
While(itr.hasNext())
{
Map.Entry m1=(Map.Entry)itr.next();
Sop(m1.getKey()+”…”+m1.getValue());
If(m1.getKey().equals(“nagarjuna”))
M1.setValue(1000);
Sop(m1);//{nagarujuna=1000,Venkatesh=200,balaiah=800,chiranjeevi=1000}
}
àLinkedHashMap:
It is the child class of HashMap
It is exactly same as HashMap Except the following difference
HashMap
LinkedHashMap
The underlying datastructure is HashTable
The underlying Datastructure is Hashtable+LinkedList
Insertion order not preserved
Insertion order preserved
Introduced in 1.2v
Introduced in 1.4v

In the above program if we replace HashMap with LinkedHashMap
The output is
{chiranjeevit=1000,balaiah=800,Venkatesh=200,nagarjuna=1000}
i.e insertion order is preserved
Identiy hashMap:
It is exactly same as hashMap except the following differences
In case of hashmap JVM will use .equals(-) method to identify duplicate keys which is meant for content comparision
But in the case of identity hashmap JVM will use “==” operator to identify duplicate keys which is meant for reference comparision
Ex: HashMap m=new HashMap()
Integer i1=new Integer();
Integer i2=new Integer();
m.put(i1,”pavan”);
m.put(i2,”kalyan”);
sop(m);
{10,’kalyan’}
i.equals(i2) is True and hence it and i2 are duplicates if we replace HashMap with identifyHashMap then i1 and i2 are not duplicate keys because i1==i2 returns flase in this caste the output is
{10=pavan,10,kalyan}
WeakHashMap:
It is exactly same as hashMap except the following difference
In the case of HashMap even though object doesn’t have any reference still it is not eligible for Garbage collector if it is associated with hashmap
i.e hashMap dominates Garbagecollector


but in the case of WeakHashMap if an object doesn’t have any reference it is always eligible for GC even though it is associated with weakHashMap i.e GC dominates WeakHashMap.

classs WeakHashMap
{
p s v main(-){

HashMap h=new HashMap();
temp t=new Temp();
m.put(t,"durga");
sop(m);
t=null;
System.gc();
Thread.sleep(5000);
sop(m);
}
}
class Temp{
public String toString(){
return "temp";
}
public void finalize(){
sop("finallize method called");
}
{
o/p: {temp=druga}
{temp=durga}
if we replace HashMap with weakhashMap then output is {temp=durga}
finalize method called
{}

SortedMap:
it is the child interface of Map if we want to represent a group of (key,value) pairs according some sorting order of keys then we should go for sorted map
sorting is possible only based on the keys but not based on values
sorted map interface defines the following 6 specific methods
object firstKey()
object lastkey()
sortedMap headMap(object key)
sortedMap tailMap(Object key)
sortedMap subMap(object key1, Object key2)
comparator comparator()

TreeMap:
the underlying data structure is Balanced Tree(RED-BLACK Tree)
Insertion order is not preserved and it is based on some sorting order of keys
if we are depending on default natural sorting order then keys should be homogeneous and comparable otherwise we will get classCaste Exception
if we are defining our own sorting then keys need not be homogeneous and comparable
there are no restrictions for values. they can be heterogeneous non-comparable
Null Acceptance:
for empty TreeMap as the first entry with null key is allowed but after inserting that entry if we are trying to insert any other entry we will get NullPointerException
for the non-empty TreeMap if we are trying to insert entry with null key then we will get NullPointerException
duplicate keys are not allowed but values can be duplicated
Constructors:
TreeMap t=new TreeMap()
for default natural sorting order
TreeMap t=new TreeMap(Comparator c)
for customized sorting order
TreeMap t=new TreeMap(sortedMap m)
TreeMap t=new TreeMap(Map m)

Ex: import java.util.*;
class TreemapDemo{
p s v main(-){
TeeMap m=new TreeMap();
m.put(100,"ZZZ");
m.put(103,"YYY");
m.put(101,"XXX");
m.put(104,106);
m.put(107,null);
//m.put("FFF","XXX");//classCasteException
key must be homogeneous
//m.put(null,"XXXX");//NullpointerException
sop(m);
}
}
o/p:{100=ZZZ, 101=XXX,103=YYY,104=106,107=null}

-->Alphabetical keys(reverse)
import java.util.*
class TreeMapDemo{
p s v main(-){
TreeMap t=new TreeMap(new mycomparator());
t.put("XXX",10);t.put("AAA",20);t.put("ZZZ",30);t.put("LLL",40);
sop(t);
}
}
class myComparator implements comparator{
public int compare(Object o1,Object o2)
{
String s1=o1.toString();
String s2=o2.toString();
return s2.compareTo(s1);
}
}
o/p:{zzz=10,XXX=10,LLL=40,AAA=30}

hashTable:
the underlying data structure is hashTable
duplicate keys are not allowed but values can be duplicated  heterogeneous objects are allowed for both keys and values
insertion order is not preserved and it is based on hashcode of the keys
null is not allowed for both kesy and vallues
everymethod present inside hashtable is synchronized and hence hashtable is Threadsafe
Constructors:
hashtable h=new hashTable()
creates an empty hashTable object with default initial
capacity '11' and default fillration 0.75
hashTable h=new HashTable(int initialcapacity)
HashTable h=new hashTable(int initialcapacity, float fillratio)
hashTable h=new hashtable(Map m)
-->based on  hashtable flow the object are sorted
import java.util.*;
class hashtableDemo{
p s v main(-)
{
Hashtable =new HashTable();
h.put(new Temp(5),"A");
h.put(new Temp(2),"B");
h.put(new Temp(6),"C");
h.put(new Temp(15),"D");
h.put(new Temp(23),"E");
h.put(new Temp(16),"F");
//h.put("durga",null);//NullpointerException
Sop(h);
}
}
class Temp{
int i;
temp(int i)
{
this.i=i;
}
public int hashCode()
{
return i;
}
public String toString()
{
return i+"";
}
}
o/p: {6=c,16=F,5=A,15=D,2=B,23=E}
-->Properties:
if any thing which changes frequently lik (username,passowrd,mailid)
etc. are never recommended to hardcode in java application. because for everychange we have to recompile and rebuild and redeploy application. and sometimes server restart also required. which creates business impact to the client.
such type of values we have to configure in properties file and we have to read those parameters for into java application  for any change in properties file just redeployment is enough which won't create any business impact to the client
we can use java properties object to hold properties which are coming from properties file
properties is the child class of hashtable
in properties both key and value are Stringtype
Constructor:
peroperties p=new Properties(0
methods;
String getProperty(String prop)
returns the value associated with specified property
String setProperty(String propname,String propvalue)
to set a new property
Enumeration propertyNames();
returns all the properties
void load(InputStream ips)
to load properties from properties file into java properties object
void store(OutputStream as, String comment)
to store properties from java properties object into properties file

-->perform I/O operations with properties file
import java.util.*;
import java.io.*;
class PropertiesDemo
{
p s v main(-){
properties p=new Properties();
fileinputStream fis=new FileInputStream("abc.properties");
p.load(fis);
sop(p)
String s=p,getProperty("venki");
sop(s);
p.setProperty("nag","8888");
FileOutPutStream fos=new FileOutPutStream("abc.properties");
p.store(fos,"updated by username");
}
}
-->abc.properties
user=tiger
pwd=scott
venki=9999

Queue(I): [1.5 v enhancements]
it is the child interface of collection. if we want to represent a group of individual objects. prior to processing then we should go for queue.
fig

from 1.5 v onwards LinkedList class also implements Queue
interface usually queue follows first in FirstOut order. but based on our requirement we can implement our own priority order also
LinkedList based implementation of queue always follows First in First Out order
Queue(I) methods:
boolean offer(Object o)
to add an object into the queue
Object peek()
it returns head element of the queue
object element()
returns head element of the queue if queue is empty then its method raises RE saying NosuchElementException
object poll()
to remove and return head element of the queue if queue is empty then this method returns null
object remove()
returns the head element of the queue and if remove queue is empty then this method throws a runtime excpetion saying NoSuchElementException

Priority QUeue:
it is the data structure which can be used to represent a group of individual objects prior to processing according to some priority
the priority can be either default natural sorting order or customized sorting order
duplicate objects are not allowed
insertionorder is not preserved
if we are depending on default natural sorting order compulsory the objects should be homogeneous and cparable otherwise we will get ClassCasteException
if we are defining our own sorting according to comparator then objects need not be homogeneous and comparable
null insertion is not possible even as the first element also

Constructors:
priorityQueue q=new PriorityQueue();
creates an empty priority queue with default initial capacity 11 and sorting order is default natural sorting order.
priorityQueue q=new PriorityQueue(int initialCapacity)
priorityQueue q=new PriorityQueue(int initialcapacity, Comparator c)
priorityqueue q=new priorityQueue(sortedSet s)
priorityqueue q=new priorityqueue (Collection c)

-->ex: Queue Demo
import java.util.*;
class priorityQueuDemo
{
p s v main(-){
priorityqueue  p=new priorityqueue ()
sop(q.peek());//null
sop(q.elements());//RE: NSEE
for(int i=0;i<=10;i++)
q.offer(i);//Loading / Insertion
sop(q);//[0,1,2,..10]
sop(q.poll());//0
sop(q);[1,2,..10]
o/p:
[0,1,2..10]
0
[1,2,...10]

Note: some operating systems like WinT may not provide proper support for priorityQueryes
Ex: according to comparator
import java.util.*
class PriorityQueru{
p s v main(-)
{
PriorityQueue p=new PriorityQueue(15, new myComparator());
p.offer("A");p.offer("Z");p.offer("L");p.offer("B");
sop(p);//[Z,L,B,A]
}
}
calss myComparator implements comparator
{
public int compare(Object o1,Object o2){
String s1=(String)o1;
String s2(String)o2;
returns s2.compareTo(s1);
}
}
o/p:[Z,L,B,A]


1.6 v Enhancements:
1Navigable Set:
it is the child interface of sortedset
this interface defines several methods for navigation purpose.
Collection(I)
Set(I)
SortedSet(I)
navigableSet(I)
TreeSet


NavigableSet defines the following methods
floar(e)
it returns highest element which is less than or (<=e)
lower(e)
it returns highest lement which is less than(<e)
ceiling(e)
it returns lowest element which is (>=e)
higher(e)
it returns lowest element which is (>e)
pollFirst()
remove and return first element
pollLast()
remove and return last element
descendingSet()
it return navigable set in reverse order

import java.util.*;
class navigableDemo{
p s v main(-)
{
TreeSet<Integer> t=new TreeSet<Integer>();
t.add(1000);t.add(2000);t.add(3000);t.add(4000);t.add(5000);
sop(t);
sop(t.ceiling(2000));
sop(t.higher(2000));
sop(t.floor(3000));
sop(t.lower(3000)));
sop(t.pullFirst());
sop(t.pullLast());
sop(t.descendingSet());
}
}
o/p:[1000,2000,3000,4000,5000]
2000
3000
3000
2000
1000
5000
[4000,300,2000]
[2000,3000,4000]

Navigable Map:
if is the child interface of SortedMap
it defines several methods for navigation purposes
Methods:
floorkey(e)
lowerkey(e)
ceilingkey(e)
higherkey(e)
pullFirstEntry()
pullLastEntry()
descendingMap();
ex: import java.util.*;
class navigableMapDemo{
p s v main(-){

TreeMap<String,String> t=new TreeMap<String,String>();
t.put("b","banana");
t.put("c","Cat");
t.put("a","apple");
t.put("d,"Dog");
t.put("g","gun");
sop(t);
sop(t.ceilingKey("c"));
sop(t.higherKey("e"));
sop(t.floorKey("e"));
sop(t.lowerKey("e"));
sop(t.pullFirstEntry());
sop(t.putllLastEntry());
sop(t.descendingMap());
sop(t);
}
}
o/p: [a=apple, b=banana, c=cat, d=dog, g=gun]
c
g
d
d
a=apple
g=gun
{d=dog,c=cat,b=banana}
[b=banana, c=cat, d=dog}


Collections Class:
Collections class is an utility class to provide several utility method for collection objects
i. sorting elements of list
collections class defines the follwoing sort methods
public static void sort(list l)
to sort elements of list according to natural sorting order compulsory list should contain homoheneous elements otherwise we will get ClassCasteException
the list should not contain null otherwise we will get NullPointerException

public static void sort(List l, comparator c)
to sort elements fo List accordint to customized sortting order

ii. Searching the elements of List
colections has defined the follwoing search emthods
 pulblic static int binarySearch(List l, Objech key)
if the list is sorted according to natural sorting order then we have to use this method
public static int binarySearch(List l, object key, Comparator c)
if the list is sorted according to comparator then we have to use this method

Conclusions: internally the above methods will use binarySearchAlgoarithm
successful search returns index usually search returns "insertion point"

Insertion point is the place where we can place the Target element in
sorted list(it is -ve) starts from -1
before calling binarysearch method compulsory list should be sorted otherwise we will get unpredictable results
if the list is sorted according to comparator then we the time of search also we should pass the same comparator object otherwise we will get unpredictable results
Note: for the list of 'n' elements
i. successfull search: 0 to n-1
ii. unsuccessfull search: -(n+1) to -1
iii. TotalResult range: -(n+1) to (n-1)

ex: for the list of five elements

Successsfull search :0 to 4
unsuccessful search: -6 to -1
total result range: -6 to 4
ii. Reversing the elements of the List:

public static void reverseList(List l)

Reverse Vs Reverse Order:
we can use Reverse() method to reverse the order of elements of list
where as
we can use reverseOrder(-) method to get reversed comparator
ex: comparator c1=Collections.reverseOrder(Comparator c);
     descendingorder                                          Ascendingorder


ArraysClass:
it is an utility class to define several utility methods for Arrays:
sorting the elements of Array
arrays class defines the following sort methods
public static void sort(primitive[] p)
to sort elements of primitive array according to natural sorting order
public static void sort(object[] o)
to sort elements of object array according to natural sorting order
public static void sort(object[] s, comparator c)
to sort elements of object array according to customized sorting order
Note: we can sort primitive arrays only based on natural sorting where as we can sort object[] either based on natural sorting or customized sorting
Searching the elements of Array
public static int binarySearch(primitive[] p, Primitive key)
public static int binarySearch(Object[] o, object key)
public static int binarySearch(Object[] o, object key, comparator c)
note: all rules of Arrays class Binary search method are exactly same as collections class binary search methods
Converting Array to List
public static list asList(Object[] a)
strictly speaking this method won't create any list object for the existing array object. just we are getting list reference
String [] s={"A","B","C"};
list l=Arrays.asList(s);


Conclustions:
by using ArrayReference if we are performing any change automatically this change will be reflected for list
similarly by using list reference if we perform any change automatically this change will be reflected to the Array
by using list reference we can't perform any operation which varies the size otherwise we will get runtime exception saying unsupported operation Exception i.e we can't perform add and remove operations but we can perform replace operation
by using List Reference if we are tyring to replace with heterogeneous objects. we will get RuntimeException Saying ArrayStoreExcpetion
l.add("K");/l.remove(1)RE: UnSupportedOperationException
l.set(1,new Integer(10));//RE: ArrayStoreException

Comments

Popular posts from this blog

Database Definition and DBMS