Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
127 views

Java Collection Notes.

Collections are used to overcome limitations of arrays, such as fixed size and only holding homogeneous elements. The key interfaces of the Java Collection Framework include Collection, List, Set, SortedSet, Queue, and Map. List allows duplicates and preserves insertion order, while Set does not allow duplicates or preserve insertion order. Map represents key-value pairs with no duplicate keys. Common implementing classes for List include ArrayList and LinkedList.

Uploaded by

ASR PANDEY
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
127 views

Java Collection Notes.

Collections are used to overcome limitations of arrays, such as fixed size and only holding homogeneous elements. The key interfaces of the Java Collection Framework include Collection, List, Set, SortedSet, Queue, and Map. List allows duplicates and preserves insertion order, while Set does not allow duplicates or preserve insertion order. Map represents key-value pairs with no duplicate keys. Common implementing classes for List include ArrayList and LinkedList.

Uploaded by

ASR PANDEY
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Need Of Collections

An array is an indexed Collection of fixed number of homogeneous data elements. The Main
advantage of Arrays is we can represent multiple values with a single variable. So that
reusability of the code will be improved.

Limitations of Object type Arrays:


1)Arrays are fixed in size i.e. once we created an array with some size there is no chance of
increasing or decreasing it's size based on our requirement. Hence to use arrays compulsory
we should know the size in advance which may not possible always.
2) Arrays can hold only homogeneous data elements.
Ex:-
Student [] s = new Student [10000];
s[0]= new Student; (correct)
s[1]= new Customer(); (wrong)
But We can resolve this problem by using object Arrays.
Object[] = new Object [10000];
o[0]= new Student();
o[1]= new Customer();
3)Arrays Concept is not implemented based on some standard data structure hence
readymade method support is not available for every requirement we have to write the code
explicitly. Which is complexity of progra iniriJRGASOPT

SOLUTIONS TO THESE PROBLEMS


To overcome the above limitations of Arrays we should go for Collections.
Collections are growbable in nature. i.e. Based on our requirement we can increase (or)
Decrease the size.
Collections can hold both homogeneous & Heterogeneous elements. Every Collection class is
implemented based on some standard data structure. Hence readymade method support is
available for every requirement. Being a programmer we have to use this method and we are
not responsible to provide implementation.

Difference between Arrays and Collections:


Arrays
1. Arrays are fixed in size.
2. Wrt memory arrays are not recommended to use.
3. Wrt Performance Arrays are recommended to use.
4. Array can hold only homogeneous datatype elements
5. There is no underlying data structure for arrays and hence readymade method support is
not available
6. Array can hold both primitives and object types
Collections
1. Collections are growable in nature. I.e. based on our requirement we can increase or
decrease the size.
2. Wrt to memory collections are recommended to use.
3. Wrt Performance collections are not recommended to use.
4. Collections can hold both homogeneous and heterogeneous elements.
5. Every Collections class is implemented based on some standard data structure. Hence
readymade method support is available for every requirement.
6. Collections can hold only objects but not primitives.
What is Collection?
If we want to represent a group of individual objects as a single entity then we should go for
Collection.

What is Collection Framework?


It defines several classes and interfaces which can be used a group of objects as single entity.

9-Key Interfaces of Collection Framework


i. Collection:
* If we want to represent a group of individual objects as a single entity then we should go for
Collection.
Collection interface defines the most common methods which are applicable for any
Collection object.
In general collection interface is considered as root interface of Collection Framework.
Note: there is no concrete class which implements collection interface directly.

Difference between Collection & Collections


* Collection is an interface which can be used to represent a group of individual objects as a
single entity.
* Collections is an utility class present in java.util.package to define several utility methods
(like Sorting, Searching..) for Collection objects.

ii. List :
* List is child interface of Collection.
* If we want to represent a group of individual objects as a single entity where duplicates are
allowed and insertion order preserved then we should go for List.

COLLECTION(I)(V1.2)

LIST(I)
(1.2V)

ARRAYLIST(C) LINKED LIST(C) (V1.0) VECTOR(C)


(V1.2) (V1.2)

(V1.0)STACK(CC)

:-SINCE VECTOR ARE AVAILABLE FROM “V1.0” THAT’S WHY WE CALL THEM
LEGACY CLASSES
:These class were reengineered for implementing list Interface

I- INTERFACE
C-CLASS
CC-CHIELD_CLASS
iii. Set:
* It is the child interface of Collection.
* If we want to represent a group of individual objects as a single entity where duplicates are
not allowed and insertion order not preserved then we should go for Set.

COLLECTION(I)
(V1.2)

SET
(V1.2)

HashSet(C) SortedSet(I)(V1.2)
(V1.2)

LinkedHashSet(C) NavigableSet(I)(V1.6)
(V1.4)

TreeSet(C)(V1.2)

iv. SortedSet:
It is the child interface of Set.
If we want to represent a group of individual objects as a single entity where duplicates are
not allowed but all objects should be inserted according to some sorting orde then we should
go for SortedSet.

Difference between List & Set


List
Duplicates are allowed
Insertion order preserved

Set
Duplicates are not allowed
Insertion order not preserved

vi. Queue:
* It is child interface of Collection.
* If we want to represent a group of individual objects prior to processing(eirlier than the
default sequence) then we should go for Queue.
Ex: before sending a mail all mail id's we have to store somewhere and in which order we
saved in the same order mail's should be delivered (First in First out) for this requirement
Queue concept is the best choice.
Note:
* All the above interfaces
(Collection, List, Set, SortedSet, NavigableSet and Queue) meant for representing a group of
individual objects.
* If we want to represent a group of objects as key value pairs then we should go for Map
Interface.

vii. Map:
* Map is not the child interface of Collection.
* If we want to represent a group of individual objects as key value pairs then should go for
Map.
Ex:
Roll No Name
101 Durga
102 Ravi
103 Venkat
Both key and value are objects, duplicated keys are not allowed but values can be duplicated

viii. SortedMap:
* It is the child interface of map.
* If we want to represent a group of key value pairs according to some sorting order of keys
then we should go for SortedMap
ix. NavigableMap:
* It is the child interface of sorted map, it defines several utility methods for navigation
purpose.

x. TreeMap:
TreeMap is a class in the Java Collections Framework that provides an
implementation of the SortedMap interface. It represents a map that is sorted
according to the natural ordering of its keys or by a custom Comparator provided
during its creation.

THE COMPLETE HIERARCHY OF COLLECTION


FRAMEWORK:
COLLECTION INTERFACE

If we want to represent group of data as a single entity then we should go for Collection.

Important Methods of Collection Interface:

boolean add(Object o)
boolean addAll(Collection c)
boolean remove(Object o)
boolean removeAll(Collection c)
boolean retainAll(Collection c)
void clear()
boolean contains(Object o)
boolean containsAll(Collection c)
boolean isEmpty()
int size()
object[] toArray()
Iterator iterator()

Note:
Collection interface doesn't contain any method to retrieve objects there is no concrete class
which implements collection class directly.
LIST INTERFACE
* It is the child interface of Collection.
* If we want to represent a group of individual objects as a single entity where duplicates are
allowed and insertion order must be preserved then we should go for List.
* We can differentiate duplicates by using index.
* We can preserve insertion order by using index, hence index play very important role in list
interface.

Important Methods of List Interface:

1.void add(int index, Object o)


2.boolean addAll(int index,Collection c)
3. Object get(int index)
4. Object remove(int index)
5 Object set(int index, Object new) : to replace the element present at specified index with
provided Object and returns old object
6.int indexOf(Object o):returns index of first occurrence of 'o'
7.int lastIndexOf(Object o)
8. ListIterator listIterator();

IMPLEMENTING CLASSES OF LIST INTERFACE

ArrayList:-
The underlined data structure Resizable Array or Growable Array
Duplicates are allowed.
• Insertion order is preserved.
Heterogeneous objects are allowed [except TreeSet & TreeMap everywhere heterogeneous
objects are allowed].
• Null insertion is possible.

ArrayList Constructors:
1. ArrayList al = new ArrayList()
Creates an empty Array list object with default initial capacity 10. Once Array List reaches its
map capacity a new Array List will be created with new capacity = (currentcapacity * 3/2) + 1.

2.ArrayList al = new ArrayList(int initialCapacity);


This Constructor creats an ArrayList of Known Capacity
3.ArrayList al = new ArrayList(Collection c);
This Constructor Creats an ArrayList of Same Size and Capacity as “Collection C”

Program To Manipulate ArrayList:


import java.util.*;
Class ArrayListDemo {
public static void main(String[] args) {
ArrayList = new ArrayList();
I.add("A");
I.add(10);
I.add("A");
I.add(null);
System.out.println(); // [A, 10, A, null]
I.remove(2);
System.out.println(); //[A, 10, null]
I.add("2", "m");
l.add("N");
System.out.println(); // [A, 10, M, null,N] } }

IMPORTANT FEATURES OF ARRAYLIST:

* Usually we can use Collections to hold and transfer Objects from one place to another place,
to provide support for this requirement every Collection already implements Serializable and
Cloneable interfaces.

*ArrayList and Vector classes implements RandomAccess interface so that we can access any
Random element with the same speed.

* Hence if our frequent operation is retrieval operation then ArrayList is the best choice.

*RandomAccess Interface:
Present in java.util package.
It doesn't contain any methods and it is a Marker interface

*ArrayList is best choice if our frequent operation is retrieval operation (Because ArrayList
implements RandomAccess interfaces)

*ArrayList is the worst choice if our frequent operation is insertion or deletion in the middle
(Because several shift operation are require)

*ArrayList 11=new ArrayList();


LinkedList 12-new LinkedList();
System.out.println (11 instanceOf Serializable); //true
System.out.println (12 instance Of Cloneable);//true
System.out.println (11 instanceOf RandomAccess); //true
System.out.println (12 instance Of RandomAccess); //false

HOW TO GET Synchronized VERSION OF ArrayList

By default ArrayList is Object is non-synchronized but we can get synchronized version of


ArrayList by using Collection class synchronizedList() method.

public static List synchronized List(List I)

Example:- public static List synchronizedList(List I)


Non-Synchronized: ArrayList 11=new ArrayList();

Synchronized List I=Collections.synchronized List (11);

Similarly 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 Set synchronizedMap (Map m);
LINKED-LIST
* The underlying data structure is Double Linked List.

* Insertion order is preserved.

* Duplicates are allowed.

* Heterogeneous Objects are allowed.

* Null insertion is possible.

* LinkedList implements Serializable and Clonable interfaces but not RandomAccess


interface.

* LinkedList is the best choice if our frequent operation is insertion or deletion in the middle.
LinkedList is the worst choice if our frequent operation is retrieval operation.

* Usually we can use LinkedList to implement stacks and queues to provide support for this
requirement LinkedList class defines following specific methods.
void addFirst();
void addLast();
Object getFirst();
Object getLast();
Object removeFirst();
Object removeLast();

LinkedList Constructors
1.LinkedList 11=new LinkedList(); Creates an empty LinkedList Object

2. LinkedList 11=new LinkedList(Collection c); Creates an equivalent LinkedList Object for


the given Collection
JAVA PROGRAM TO MANIPULATE LINKED-LIST
import java.util.*;
public class LinkedListDemo {
public static void main() {
LinkedList 11=new LinkedList();
11.add("durga");
11.add (30);
11.add (null);
11.add("durga");
11.set (0,"software");
11.add (0,"venkey");
11.addFirst ("ccc");
System.out.println (1);//[ccc,venkey,software,30,null]
}
DIFFRENCE BETWEEN ARRAYLIST AND LINKEDLIST

VECTOR
* The underlying Data structure for the vector is resizable array or growable array.
* Duplicate objects are allowed.
* Insertion order is preserved.
* 'null' insertion is possible.
* Heterogeneous objects are allowed.
* Vector class implemented Serializable, Cloneable and RandomAccess Interfaces.
* Most of the methods present in Vector are synchronized. Hence Vector object is
Thread-safe.
* Best choice if the frequent operation is retrieval

Vector specific methods:


For adding objects:
add (Object o)
add (int index, Object o)
addElement (Object o)
[from Collection - List(I)]
[from List]
[from Vector]
For removing Objects:
Remove (Object o):[from Collection ]
removeElement (Object o):[from Vector ]
remove (int index):[from List]
RemoveElementAt (int index):[from Vector]
clear ()[ from Collection]
removeAllElements ():[ from Vector ]
For Accessing Elements:
Object get (int index):[from Collection]
Object elementAt (int index):[ from Vector ]
Object firstElement():[ from Vector]
Object lastElement():[from Vector ]
Other Methods:
int size();
int capacity ();
Enumeration elements ();

Constructors of vector class


1) Vector v = new Vector();
import java.util.*;
class VectorDemo {
public static void main(String arg[]) {
Vector v = new Vector ();
System.out.println (v.capacity ());
for (int i=0;i<10;i++) {
v.addElement (i); //[10]
}
System.out.println (v.capacity ());
v.addElement("A");
System.out.println (v); //[10] //[20]
System.out.println (v.capacity ());
}
}
- Creates an empty vector object with default initial capacity 10, Once vector reaches it's max
capacity a new vector Object will be Created with new capacity = 2 * current capacity.
2) Vector v = new Vector(int initialCapacity);
import java.util.*;
class VectorDemo {
public static void main(String[] args) {
Vector v = new Vector(25));
System.out.println(v.capacity()); for(int i = 1; i<=10; i++)
{
v.addElement(i);
}
System.out.println(v.capacity());
v.addElement("A");
System.out.println(v.capacity());
System.out.println(v); //[1,2,,,,10,A]
}
}

- Creates an empty Vector Object with specified initial capacity


3) Vector v = new Vector(int initialCapacity, int incrementalCapacity);
import java.util.*;
class VectorDemo1
{
public static void main(String[] args) {
Vector v = new Vector(10,5);
System.out.println(v.capacity()); I
for(int i = 1; i<=10; i++)
{
v.addElement(i);
}
System.out.println(v.capacity());
v.addElement("A");
System.out.println(v.capacity());
System.out.println(v);//[1,2,10,A]
}
}
4) Vector v = new Vector(Collection c);
import java.util.*;
class VectorDemo {
public static void main(String[] args) {
Vector v1 = new Vector(v));
System.out.println(v.capacity()); for(int i = 1; i<=10; i++)
{
v.addElement(i);
}
System.out.println(v.capacity());
v.addElement("A");
System.out.println(v.capacity());
System.out.println(v); //[1,2,,,,10,A]
}
}
this program ultimately creates another Vector which is identiccal to another Vector created
above named “V”
- Creates an equivalent Vector Object for the given Collection

DIFFERENCE BETWEEN ArrayList and Vector:-


STACK
* It is a child class of Vector.
* It is specially designed class for Last In First Out order(LIFO)

Constructor of Stack
Stack s=new Stack ();

Methods in Stack
1) Object push(Object obj);
- For inserting an object to the stack
2) Object pop();
- To removes and returns top of the stack.
3) Object peak();
- To Returns the top of the stack without removal of object.
4) int search(Object obj);
- If the specified object is available it returns its offset from top of the stack.
- If the object is not available then it returns -1.
5) Object pop();
- For inserting an object to the stack

EXAMPLE:-
import java.util.*;
class StackDemo {
public static void main (String arg[]) {
Stack s = new Stack ();
s.push ("A");
s.push("B");
s.push ("C");
System.out.println(s); //[A,B,C] System.out.println (s.search ("A")); //[3]
System.out.println (s.search("Z")); //[-1]
}
}
SET
SET
1. Set is the child interface of Collection.
2. If we want to represent a group of individual objects as a single entity, where duplicates are
not allowed and insertion order is not preserved then we should go for Set.
3. Set interface doesn't contain any new methods. So we have to use only Collection interface
methods.
HashSet
*The underlying data structure is Hashtable.
* Duplicates are not allowed. If we are trying to insert duplicates, we won't
get any compiletime or runtime errors. add() method simply returns false.
* Insertion order is not preserved and all objects will be inserted based on hash-code of
objects.
*Heterogeneous objects are allowed.
*'null'insertion is possible.
* implements Serializable and Clonable interfaces but not RandomAccess.
*HashSet is the best choice, if our frequent operation is Search operation.

Constructors of HashSet

1) HashSeth = new HashSet();

import java.util.*;
class HashSetDemo {
public static void main (String[] args) {
HashSet h=new HashSet ();
h.add("B");
h.add("C");
h.add("D");
h.add("Z");
h.add(null);
h.add(10);
System.out.println (h.add("Z")); // false
System.out.println (h); // [null, D, B, C, 10, Z]
}
}
- Creates an empty HashSet object with default initial capacity 16 & default Fill Retio 0.75
2) HashSet h = new HashSet(int initalCapacity);
- Creates an empty HashSet object with specified initial capacity & default Fill Retio 0.75
3) HashSeth = new HashSet(int initalCapacity, float loadFactor);
- Creates an empty HashSet object with specified initial capacity & specified Load Factor (or
Fill Ratio)
4) HashSet h = new HashSet(Collection c);

Load Factor / Fill Ratio:


- After loading the how much factor, a new HashSet object will be created, that factor is called
as Load Factor or Fill Ratio.
LnkedHashSet

import java.util.*;
class LinkedHashSetDemo {
public static void main(String[] args) {
LinkedHashSet h=new LinkedHashSet ();
h.add("B");
h.add("C");
h.add("D");
h.add("Z");
h.add(null);
h.add(10);
System.out.println (h.add("Z")); // false
System.out.println (h); // [B, C, D, Z, null, 10]
}
}
THE OUTPUT IS IN PRESERVED ORDER

Note:
- LinkedHashSet is the best choice to develop cache based applications, where duplicates are
not allowed and insertion order must be preserved.
SortedSet(I)
1. It is the child interface of set.
2. If we want to represent a group of individual objects according to some sorting order and
duplicates are not allowed then we should go for SortedSet.
SortedSet Specific methods
1.Object first()
- returns first element of the SortedSet
2.Object last()
- returns last element of the SortedSet
3.SortedSet headSet(Object obj) - returns the SortedSet whose elements are <obj
4.SortedSet tallSet(Object obj)
- returns the SortedSet whose elements are >= obj
5.SortedSet subset(Object obj1, Object obj2)
- returns the SortedSet whose elements are >= obj1 and <obj2
6.Comparator comparator()
- returns Comparator object that describes underlying sorting technique. If we are using
default natural sorting order then we will get null.

Example:{100,101,103,104,107,110,115}
1. first():100
2. last():-> 115
3. headset(104) -> [100,101,103]
4. tailSet(104) -> [104,107,110,115]
5. subset(103,110) →> [103,104,107]
6. comparator() → null
Note:
1. Default natural sorting order for numbers Ascending order and for String alphabetical
order.
2. We can apply the above methods only on SortedSet implemented class objects. That is on
the TreeSet object.

NavigableSet

It is the chield interface of SortedSet Interface and It defines several methods for navigation
purposes.
METHODS
1.floor(e) :returns highest element which is e<=Element
2.lower(e):returns highest element which is e<Element
3.ceiling(e):returns lowest element whch is e>=Element
4.higher(e):returns lowest element which is e<Element
5.pollFirst():removes and returns first element
6.pollLast():removes and returns last element
7.descendingSet():reverses the order of the set and returns it.
TreeSet
1. The underlying data structure for TreeSet is Balanced Tree.
2. Duplicate objects are not allowed.
3. Insertion order not preserved, but all objects will be inserted according to some sorting
order.
4. Heterogeneous objects are not allowed. If we are trying to insert heterogeneous objects then
we will get runtime exception saying ClassCastException.
5. Null Insertion is allowed, but only once.

TreeSet Constructors
1. TreeSet t=new TreeSet();
- Creates an empty TreeSet object where elements will be inserted according to default
natural sorting order.
2. TreeSet t-new TreeSet(Comparator c);
- Creates an empty TreeSet Object where elements will be inserted according to customized
sorting order.
3. TreeSet t-new TreeSet(SortedSet s);
4. TreeSet t=new TreeSet(Collection c);

Example:
import java.util.*;
class TreeSetDemo {
public static void main(String[] args) {
TreeSett = new TreeSet();
t.add("A");
Ladd("a");
Ladd("B");
Ladd("Z");
Ladd("L");
// L.add(new Integer(10)); // ClassCastException
L.add(null); // NullPointerException
System.out.println(t); // (A, B, L, Z, a]
}
}

Null Acceptance
1. For empty TreeSet as the first element null insertion is possible. But After inserting that
null if we are trying to insert any another element we will get NullPointerException.
2. For Non empty TreeSet If we are trying to insert Null then we will get
NullPointerExcpetion.

Example
import java.util.TreeSet;
class TreeSetDemo1 {
public static void main(String[] args) {
t.add(new StringBuffer("A"));
TreeSett = new TreeSet();
t.add(new StringBuffer("Z"));
t.add(new StringBuffer("L"));
t.add(new StringBuffer("B"));
System.out.println(t); // ClassCastException}}
Note:
1. If we are depending on default natural sorting order then objects should be homogeneous
and comparable. Otherwise we will get runtime exception saying ClassCastException.
2. An object is said to be comparable if and only if the corresponding class implements
java.lang.comparable interface.
3. String Class and all wrapper classes already implements comparable interface. But
StringBuffer doesn't implement comparable interface.
** Hence in the above program we got ClassCastException **

Comparable Interface
*This interface present in java.lang package it contains only one method CompareTo().
public int CompareTo(Object obj)
Example:
obj1.CompareTo(obj2)
==returns -ve iff obj1 has to come before obj2
==returns +ve iff obj1 has to come after obj2
==returns 0 iff obj1 & obj2 are equal.

Example
class Test {
public static void main(String[] args) {
System.out.println("A".compareTo("Z")); //-ve
System.out.println("Z".compareTo("B")); // +ve
System.out.println("A".compareTo("A")); //0
System.out.println("A".compareTo(null)); // NullPointerException
}
}

Comparator Interface
* We can use comparator to define our own sorting (Customized sorting).
* Comparator interface present in java.util package.
* It defines two methods. compare and equals.

1) public int compare(Object obj1, Object obj2)


->returns-ve iff obj1 has to come before obj2
->returns +ve iff obj1 has to come after obj2
-> returns 0 iff obj1 & obj2 are equal.

2) public boolean equals();

*When ever we are implementing Comparator interface, compulsory we should provide


implementation for compare() method.
* And implementing equals() method is optional, because it is already available in every java
class from Object class through inheritance.
Write A Program to insert integer objects into the TreeSet where the sorting order
is descending order:

Integer Objects Into TreeSet, Desending order:


Treesett=new Treeset(new MyComparator());
t.add(10);
t.add(0); +ve →→→ compare(0,10);
t.add(15); -ve->compare(15,10); -
t.add(20);+ve-compare(20,10);
t.add(20);-ve-compare(20,15);
t.add(20); +ve →→→ compare(20,10);
t.add(20); -ve-compare(20,15);
t.add(20);->Compare(3020):

* At line-1 if we are not passing comparator object then internally JVM will call CompareTo()
method which meant for default natural sorting order (ascending order).
In this case output is [0,10,15,20].
*If we are passing comparator object at line 1 then internally JVM will call compare() method
which is meant for customized sorting.
(Descending order). In this case output is [20,15,10,0]
Note:
* If we are defining our own sorting by Comparator, the objects need not be
Comparable.

Note:
1.If we are depending on default natural sorting order then objects should be
homogeneous and comparable otherwise we will get runtime exception saying
ClassCastException.
2.But if we are defining our own sorting by comparator then objects need not be
homogeneous and comparable. we can insert heterogeneous non comparable
objects also.

3) For predefined Comparable classes like String default natural sorting order
already available. If we are not satisfied with that, we can define our own sorting
by Comparator object.
4) For Predefined non comparable classes like StringBuffer, default natural
sorting order is not already available. We can define required sorting by
implementing Comparator interface.
5) For our own classes like Employee, Student, Customer), the person who is
writing our own class, he is responsible to define default natural sorting order by
implementing Comparable interface.
The person who is using our class, if he is not satisfied with default natural
sorting order, then he can define his own sorting by using Comparator.
Demo program for Customized sorting for Employee class: (Page 1 of 3)
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() { retum name+"-"+eid;
}
public int compareTo(Object obj) {
int eid1 = this.eid;
Employee e=(Employee)obj; int eid2 = e.eid;
if(eid1<eid2){
return -1;
}else if (eid1>eid2) {
retum 1;
} else {
return 0;
}
}
class CompCompDemo {
public static void main(String[] args) {
Employee e1 = new Employee("nag",100);
Employee e2= new Employee("balalah",200);
Employee e3= new Employee("chiru",50); TreeSet t= new TreeSet(); } }
Employee e4 = new Employee("venkd",150);
Employee e5= new Employee("nag",100)
TreeSet t1=new TreeSet();
t.add(e1);
t.add(e2);
t.add(e3);
t.add(e4);
t.add(e5);
System.out.println(t);
TreeSet t1=new TreeSet(new MyComprator());
t.add(e1);
t1.add(e2);
t1.add(e3);
t1.add(e4);
t1.add(e5);
System.out.println(t);
}
}
Queue interface
1) If we want to represent a group of individual objects prior
(happening before something else) to processing then we should go
for Queue interface.

Collection(1)(1.2)

Queue(1)

PriorityQueue BlockingQueue(1)

PriorityBlockingQueue

LinkedBlockingQueue
List(I) -->LinkedList(C)
2) Usually Queue follows first in first out order but based on our
requirement we can implement our own order also.

Queue interface methods:


1) boolean after(Object o);----> To add an object to the Queue.
2) Object poll() ;--->To remove and return head element of the Queue,
if Queue is empty then we will get
null.
3) Object remove();--->To remove and return head element of the
Queue. If Queue is empty then this method raises Runtime Exception
saying NoSuchElementException.
4) Object peek();--->To return head element of the Queue without
removal, if Queue is empty this method returns null.
5) Object element();-->It returns head element of the Queue and if
Queue is empty then it will raise Runtime Exception saying
NoSuchElementException.

PriorityQueue
1) We can use PriorityQueue to represent a group of individual objects
prior to processing
according to some priority.
2) The priority order can be either default natural sorting order (or)
customized sorting
order specified by Comparator object.
3) From 1.5v onwards LinkedList also implements Queue interface.
4) It we are defining our own customized sorting order by Comparator
then the objects need not be homogeneous and Comparable.
5) Duplicate objects are not allowed.
6) Insertion order is not preserved but all objects will be inserted
according to some priority.
7) Null is not allowed even as the 1" element for empty PriorityQueue.

Constructors:
1) PriorityQueue q=new PriorityQueue();
• Creates an empty PriorityQueue with default initial capacity 11 and
default natural sorting order.
2) PriorityQueue q=new PriorityQueue(int initialcapacity, Comparator
c);
3) PriorityQueue q=new PriorityQueue(int initialcapacity);
4) PriorityQueue q=new PriorityQueue(Collection c);
5) PriorityQueue q=new PriorityQueue(SortedSets);

Example 1:
import java.util
class PriorityQueueDemo
public static void main(String[] args)
PriorityQueue q=new PriorityQueued():
//System.out.println(q.peek0)//null
//System.out.println(q.clement());//NoSuchElementException Fortint -
0-10++)
q.offer(i):
System.out.println(q)//[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
System.out.println(q.p://0
System.out.println(0)://11, 3, 2, 7,4,5,6, 10, 8, 91
}
}
Note: Some platforms may not provide proper supports for
PriorityQueue windowsXP)

Example 2:
import java.util.":
class PriorityQueueDemo
public static void main(String[] args)
PriorityQueue q=new PriorityQueue(15,new MyComparator}}:
goffer("A":
qoffer(""),
q.offer("L");
qoffer("B"
System.out.println(4).//Z, 8, L. A
class MyComparator implements Comparator{
public int compare(Object obj1, Object obj?){
String s1-(String)obj1;
String s2=obj2.toString();
return s2.compareTo(s1);
}
}

MAP(INTERFACE)

1) If we want to represent a group of objects as “key-value” pair then we should


go for Map interface.
2) Both key and value are objects only.
3) Duplicate keys are not allowed but values can be duplicated
4) Each key-value pair is called “one entry”.
5)Map interface is not child interface of Collection and hence we can’t apply
Collection interface methods here.
6)Map interface defines the following specific methods. 1) Object put(Object
key,Object value);
7)To add an entry to the Map, if key is already available then the old value
replaced with new value and old value will be returned

Map interface defines the following specific methods.


1) Object put(Object key,Object value); :To add an entry to the Map, if key is
already available then the old value replaced with new value and old value will
be returned.

Example:
import java.util.*;
class Map {
public static void main(String[] args) {
HashMap m=new HashMap();
m.put("100","vijay");
System.out.println(m);//{100=vijay}
m.put("100","bhaskar");
System.out.println(m);//{100=bhaskar
}
}
2) void putAll(Map m);
3) Object get(Object key);
4) Object remove(Object key); : It removes the entry associated with specified
key and returns the corresponding value.
5) boolean containsKey(Object key);
6) boolean containsValue(Object value);
7) boolean isEmpty();
8) Int size();
9) void clear();
10) Set keySet(); : The set of keys we are getting.
11) Collection values(); : The set of values we are getting.
12) Set entrySet();  The set of entryset we are getting."
MAP INTERFACE IMPLEMENTING CLASSES

HashMap :-

1) The underlying data structure is Hashtable.

2) Duplicate keys are not allowed but values can be duplicated.

3) Insertion order is not preserved and it is based on hash code of the keys.

4) Heterogeneous objects are allowed for both key and value.

5) Null is allowed for keys(only once) and for values(any number).

Constructors in HashMap:
1) HashMap m=new HashMap(); :Creates an empty HashMap object with default
initial capacity 16 and default fill ratio “075”.

2) HashMap m=new HashMap(int initialcapacity);

3) HashMap m =new HashMap(int initialcapacity, float fillratio);

4) HashMap m=new HashMap(Map m);"

"How to get synchronized version of HashMap:  By default


HashMap object is not synchronized. But we can get synchronized version by
using the following method of Collections class.

public static Map synchronizedMap(Map m1)


Example
"import java.util.*;

class HashMapDemo {

public static void main(String[] args) {

HashMap m=new HashMap();

m.put("chiranjeevi",700);

m.put("balaiah",800);

m.put("venkatesh",200);

m.put("nagarjuna",500); System.out.println(m);//{nagarjuna=500,
venkatesh=200, balaiah=800, chiranjeevi=700}
System.out.println(m.put("chiranjeevi",100));//700

Set s=m.keySet();

System.out.println(s);//[nagarjuna, venkatesh, balaiah, chiranjeevi]


Collection c=m.values();

System.out.println(c);//[500, 200, 800, 100]

Set s1=m.entrySet();

System.out.println(s1);//[nagarjuna=500, venkatesh=200,
balaiah=800, chiranjeevi=100]

Iterator itr=s1.iterator();

while(itr.hasNext())

Map.Entry m1=(Map.Entry)itr.next();
System.out.println(m1.getKey()+"......"+m1.getValue());//nagarjuna......500
//venkatesh......200 //balaiah......800 //chiranjeevi......100
if(m1.getKey().equals("nagarjuna"))

m1.setValue(1000);

System.out.println(m);//{nagarjuna=1000, venkatesh=200,
balaiah=800, chiranjeevi=100} }"

}}
LinkedHashMap

It is chield class of HashMap and is almost same as HashMap except for:

In the above program if we are replacing HashMap with LinkedHashMap then


the output is {chiranjeevi=100, balaiah......800, venkatesh......200,
nagarjuna......1000} that is insertion order is preserved.

Note: in general we can use LinkedHashSet and LinkedHashMap for


implementing cache applications

IdentityHashMap
1) It is exactly same as HashMap except the following differences.

2) In the case of HashMap JVM will always use “.equals()”method to identify


duplicate keys.

3) But in the case of IdentityHashMap JVM will use== (double equal operator) to
identify duplicate keys."

Example :
class IdHmap{
public static void main(String args[]){
HashMap H=new HashMap();
Integer i=new Integer(10);
Integer ii=new Integer(10);
H.put(i,”Home”);
H.put(ii,”House”);
System.out.println(i==ii);
System.out.println(i.equals(ii));
}
}
WeakHashMap
It is exactly same as HashMap except the following differences.

In the case of normal HashMap, an object is not eligible for GC even though it
doesn’t have any references if it is associated with HashMap. That is HashMap
dominates garbage collector.

But in the case of WeakHashMap if an object does not have any references then
it’s always eligible for GC even though it is associated with WeakHashMap that
is garbage collector dominates WeakHashMap.

Example:

import java.util.*;

class WeakHashMapDemo {

public static void main(String[] args)throws Exception

WeakHashMap m=new WeakHashMap();

Temp t=new Temp();

m.put(t,"bhaskar");

System.out.println(m);//{Temp=bhaskar}

t=null;

System.gc();

Thread.sleep(5000);

System.out.println(m);//{} } }

class Temp {

public String toString()

{ return "Temp"; }

public void finalize() { System.out.println("finalize() method called"); }

Output: {Temp=bhaskar}

finalize() method called"


SortedMap
It is the child interface of Map.

If we want to represent a group of key-value pairs according to some sorting


order of keys then we should go for SortedMap.

Sorting is possible only based on the keys but not based on values.

SortedMap interface defines the following 6 specific


methods.
1) Object firsyKey();

2) Object lastKey();

3) SortedMap headMap(Object key);

4) SortedMap tailMap(Object key);

5) SortedMap subMap(Object key1,Object key2);

6) Comparator comparator();
TreeMap
1) The underlying data structure is RED-BLACK Tree.

2) Duplicate keys are not allowed but values can be duplicated.

3) Insertion order is not preserved and all entries will be inserted according to
some sorting order of keys.

4) If we are depending on default natural sorting order keys should be


homogeneous and Comparable otherwise we will get ClassCastException.

5) If we are defining our own sorting order by Comparator then keys can be
heterogeneous and non Comparable. 377

6) There are no restrictions on values they can be heterogeneous and non


Comparable.

7) For the empty TreeMap as first entry null key is allowed but after inserting
that entry if we are trying to insert any other entry we will get
NullPointerException.

8) For the non empty TreeMap if we are trying to insert an entry with null key we
will get NullPointerException.

9) There are no restrictions for null values."

Constructors:
1) TreeMap t=new TreeMap();  For default natural sorting order.

2) TreeMap t=new TreeMap(Comparator c);  For customized sorting order.

3) TreeMap t=new TreeMap(SortedMap m);

4) TreeMap t=new TreeMap(Map m);


Example1: 
import java.util.*;

class TreeMapDemo

public static void main(String[] args) {

TreeMap t=new TreeMap();

t.put(100,"ZZZ");

t.put(103,"YYY");

t.put(101,"XXX");

t.put(104,106);

t.put(107,null);

//t.put("FFF","XXX");//ClassCastException
//t.put(null,"xxx");//NullPointerException

System.out.println(t);//{100=ZZZ, 101=XXX, 103=YYY, 104=106, 107=null} } }"

Example2:import java.util.*;

class TreeMapDemo

public static void main(String[] args)

TreeMap t=new TreeMap(new MyComparator());

t.put("XXX",10); 378

t.put("AAA",20);

t.put("ZZZ",30);

t.put("LLL",40);

System.out.println(t);//{ZZZ=30, XXX=10, LLL=40, AAA=20} } }


class MyComparator implements Comparator

public int compare(Object obj1,Object obj2)

{ String s1=obj1.toString();

String s2=obj2.toString(); return s2.compareTo(s1); } }"


HashTable
1) The underlying data structure is Hashtable.

2) Insertion order is not preserved and it is based on hash code of the keys.

3) Heterogeneous objects are allowed for both keys and values.

4) Null key (or) null value is not allowed otherwise we will get
NullPointerException.

5) Duplicate keys are allowed but values can be duplicated.

Constructors: 1) Hashtable h=new Hashtable();  Creates an empty


Hashtable object with default initialcapacity 11 and default fill ratio 0.75.

2) Hashtable h=new Hashtable(int initialcapacity);

3) Hashtable h=new Hashtable(int initialcapacity,float fillratio);

4) Hashtable h=new Hashtable (Map m);

Example:
import java.util.*;

class HashtableDemo {

public static void main(String[] args)

Hashtable h=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");

System.out.println(h);//{6=C, 16=F, 5=A, 15=D, 2=B, 23=E} } }

class Temp {

int i;

Temp(int i)

{ this.i=i; }

public int hashCode() { return i; }

public String toString() { return i+""; } }


Properties

1) Properties class is the child class of Hashtable.

2) If anything which changes frequently such type of values not recommended


to hardcode in java application because for every change we have to recompile,
rebuild and 381 redeployed the application and even server restart also
required sometimes it creates a big business impact to the client.

3) Such type of variable things we have to hardcode in property files and we


have to read the values from the property files.

4) The main advantage in this approach is if there is any change in property files
automatically those changes will be available to java application just
redeployment is enough.

5) By using Properties object we can read and hold properties from property
files into java application.

Constructors
Properties p=new Properties();

In properties both key and value “should be String type only

Methods: 1) String getPrperty(String propertyname) ; Returns the value


associated with specified property.

2) String setproperty(String propertyname,String propertyvalue);  To set a new


property.

3) Enumeration propertyNames();

4) void load(InputStream is);//Any InputStream we can pass.  To load Properties


from property files into java Properties object.

5) void store(OutputStream os,String comment);//Any OutputStream we can


pass.  To store the properties from Properties object into properties file.
Example:
import java.util.*;

import java.io.*;

class PropertiesDemo {

public static void main(String[] args)throws Exception

Properties p=new Properties();

FileInputStream fis=new FileInputStream("abc.properties");


p.load(fis);

System.out.println(p);//{user=scott, password=tiger,
venki=8888}

String s=p.getProperty("venki");

System.out.println(s);//8888

p.setProperty("nag","9999999");

Enumeration e=p.propertyNames();
while(e.hasMoreElements())

String s1=(String)e.nextElement();
System.out.println(s1);//nag //user //password
//venki } FileOutputStream fos=new
FileOutputStream("abc.properties");

p.store(fos,"updated by bhaskar for scjp demo


class"); } }

Property file

You might also like