0% found this document useful (0 votes)
67 views95 pages

Unit IV Collections1

This document discusses the Java Collection Framework. It introduces key interfaces like Collection, List, Set, SortedSet, NavigableSet, Queue, Map, SortedMap and NavigableMap. It describes classes that implement these interfaces like ArrayList, LinkedList, HashSet, TreeSet, PriorityQueue, HashMap and TreeMap. It also compares arrays and collections and explains differences between Collection and Collections.

Uploaded by

hasan zahid
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views95 pages

Unit IV Collections1

This document discusses the Java Collection Framework. It introduces key interfaces like Collection, List, Set, SortedSet, NavigableSet, Queue, Map, SortedMap and NavigableMap. It describes classes that implement these interfaces like ArrayList, LinkedList, HashSet, TreeSet, PriorityQueue, HashMap and TreeMap. It also compares arrays and collections and explains differences between Collection and Collections.

Uploaded by

hasan zahid
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 95

Unit-IV

Collections Framework

This work is created by N.Senthil madasamy, Dr. A.Noble Mary Juliet, Dr. M. Senthilkumar and is licensed under a
Creative Commons Attribution-ShareAlike 4.0 International License
Why Collection classes ?
int a;
int b;
10000 variables
Array:-
class Employee;
Employee Emp[]=new Employee[1000];
Emp-1 Emp-2 Emp -
1000

Index Index Index


0 1 999
Array Limitations:
1.Fixed in size
2. Homogeneous data
3. Data structure based methods not
available
Array vs Collections
Array Collections
1.Fixed in size 1.Growable in nature
2. Homogeneous data 2. Heterogeneous data
3. Data structure based 3. DS based readymade
methods not available methods
What is Collection?
Collection is representation of group of
individual objects as a single entity

What is Collection framework ?


Collection framework defines several classes
and interfaces which can be used a group of
objects as single entity.
Java C++

Collection Container

Collection Framework STL


(standard
template
library)
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
•There are 9-Key Interfaces are available in
Collection Framework ……
Collection Framework
1-Collection
• Collection represent a group of individual objects as
a single entity
• Collection interface defines the most common
methods which are applicable for any collection
object
• Collection interface is consider as root interface of
collection frame work.
• There is no concrete class which implements
collection interface directly.
Collection Framework
2-List
•List is a child interface of collection.

•It represent a group of individual objects as a


single entity where duplicates are allowed and
insertion order preserved
Collection
(1.2)

List
(1.2)

ArrayList LinkedList Vector


(1.2) (1.2) (1.2)

Stack
(1.2)
Legacy Classes
Collection Framework
3-Set
•It is the child interface of Collection

•It represent a group of individual objects as


single entity where duplicates are not allowed
and insertion order not preserved
Collection
(1.2)

Set
(1.2)

HashSet
(1.2)

Linked HashSet
(1.4)
Collection Framework
4-SortedSet
•It is the child interface of Collection

•It represent a group of individual objects as


single entity where duplicates are not allowed
but all the objects should be inserted
according to some sorting order.
Collection Framework
5-Navigable set
•It is the child interface of SortedSet
•It defines several methods for navigation
purposes
–Accessing fist data, next data , previous data
Collection
(1.2)

Set
(1.2)

SortedSet
(1.2)

NaviableSet
(1.6)

TreeSet
(1.2)
Collection Framework
6-Queue
•It is the child interface of Collection

•It represent a group of individual objects Prior


to processing.
–Eg: Sending a mail
•all mail id’s have to sore some where in some order
Collection
(1.2)

Queue
(1.5)

PriorityQueue
(1.5) BlockingQueue
(1.5)

Priority BlockingQueue LinkedBlockingQueue


(1.5) (1.5)
Collection Framework
•All the above interfaces (Collection, List, Set,
SortedSet , NavigableSet, Queue) meant for
representing a group of individual objects.

•To represents a group of objects with key


value pairs => Map Interfaces.
Collection Framework
7-Map
•Map is not the child interface of collection
•It represents a group of objects with key
value pairs Ticket Customer name

A01 Raj
A02 Sam
A03 Ravi

•both key and value are objects


• duplicated keys are not allowed but values
can be duplicated
Map
(1.2)

Dictionary
(1.0)

HashMap WeakHashMap IdentifyHashMap HashTable


(1.2) (1.2) (1.4) (1.0)

LinkedHashMap Properties
(1.4) (1.0)

Legacy Classes
Collection Framework
8-SortedMap
•It is the child interface of Map
•It represents a group of objects with key
value pairs according to some sorting order of
keys
Map
(1.2)

SortedMap
(1.2)
Collection Framework
9-Navigable Map
•It is the child Map
interface of (1.2)

SortedMap
•It defines SortedMap
(1.2)
utility
methods for
NaviableMap
navigation (1.6)

purpose
TreeMap
(1.2)
Collections Framework
Methods of Collection interface
Method Description
public boolean add(Object element) is used to insert an element in this collection.
s:
public boolean addAll(Collection c) is used to insert the specified collection elements in
the invoking collection.
public boolean remove(Object element) is used to delete an element from this collection.
public boolean removeAll(Collection c) is used to delete all the elements of specified
collection from the invoking collection.
public boolean retainAll(Collection c) is used to delete all the elements of invoking
collection except the specified collection.
public int size() return the total number of elements in the collection.
public void clear() removes the total no of element from the collection.
public boolean contains(Object element) is used to search an element.
public boolean containsAll(Collection c) is used to search the specified collection in this
collection.
public Iterator iterator() returns an iterator.
public Object[] toArray() converts collection into array.
public boolean isEmpty() checks if collection is empty.
public boolean equals(Object element) matches two collection.
public int hashCode() returns the hashcode number for collection.
List(I)
public interface List<E> extends Collection<E>
void add(int index, Object element) It is used to insert element into the
invoking list at the index passed in the
index.
boolean addAll(int index,Collection c) It is used to insert all elements of c into the
invoking list at the index passed in the
index.
object get(int index) It is used to return the object stored at the
specified index within the invoking
collection.
object set(int index,Object element) It is used to assign element to the location
specified by index within the invoking list.

object remove(int index) It is used to remove the element at position


index from the invoking list and return the
deleted element.

ListIterator listIterator() It is used to return an iterator to the start


of the invoking list.
ListIterator listIterator(int index) It is used to return an iterator to the
invoking list that begins at the specified
index.
Collection
(1.2)

List
(1.2)

ArrayList LinkedList Vector


(1.2) (1.2) (1.2)

Stack
(1.2)
Legacy Classes
ArrayList

•Resizeable Array
•Duplicates are allowed
•Insertion order is preserved
•Heterogeneous object are allowed
– expect TreeSet & TreeMap because of
heterogeneous objects
•Null insertion is possible
Constructor
•ArrayList object=new ArrayList()
–Create an empty Array list object with default initial
capacity 10.
–Once Array List reaches its capacity new ArrayList will be
created with new Capacity
–New capcity =(Current capacity * 3/2)+1

•ArrayList object =new ArrayList(int initialCapacity);

•ArrayList object=new ArrayList(Collection c);


import java.util.*;
public class ListExample{
public static void main(String args[]){

ArrayList al=new ArrayList();


al.add("A");
al.add(1);
al.add("A");
al.add(null);
System.out.println(al);
al.remove(2);
System.out.println(al);
[A,1,A,null]
al.add(2,"B"); [A,1,null]
System.out.println(al);
al.add("C");
System.out.println(al);
[A,1,B,null]
}
} [A,1,B,null,
C]
Additional Interfaces
•Serializable
•Cloneable
•Random Access
–Any random element can be access with same speed.
•Eg: First element access at 1 sec then 100th element also
access at 1 sec 100000th element also.
–Java.util.RandomAccess
–It does not contain any methods, it is a Marker
interface
Additional Interfaces
•Collection helps to transfer objects from one
place to another place, to provide support for
this requirement every collection implements
Serializable and Cloneable interfaces.
•ArrayList and vector classes implements
RandomAccess interface
ArrayList -Application
•Worst choice ?????
•Best choice ?????

Pulse Question
ArrayList -Application
•Frequent operation is retrieval operation –
best choice [RandomAccess interface]
•Frequent operation is insertion or deletion in
the middle –Worst choice [needs several shift
operation ]
Write a java program using menu to create a list for the following operations
insert an element ,retrieve an element ,remove any given element search
an element
import java.util.*;
public class ListExample{
public static void main(String args[]){
ArrayList l1=new ArrayList();
Scanner s=new Scanner(System.in);
int choice;
do{
System.out.println("List");
System.out.println("1.Insert Element into List");
System.out.println("2.Retrive Element from List");
System.out.println("3.Remove Element into List");
System.out.println("4.Search Element into List");
System.out.println("5.Exit");
choice =s.nextInt();
switch(choice)
{
case 1: System.out.println("Enter Element into List");
l1.add(s.nextInt()); break;
case 2: System.out.println("Enter Index to retrive from List");
System.out.println(l1.get(s.nextInt()));break;
case 3: System.out.println("Enter Index remove from List");
l1.remove(s.nextInt());break;
case 4: System.out.println("Enter Element to search from List"); int
x=s.nextInt();
for(int k=0;k<l1.size();k++)
if ((int)l1.get(k)==x) System.out.println(x+" is availabe at "+ k);
break;
}
System.out.println("Now the List is "+l1);
System.out.println(“ Do you want press 1 to continue press 5 to close");
choice =s.nextInt();
}while(choice!=5);
Linked List
Linked List
•Double linked list
•Insertion order is preserved
•Duplicates are allowed
•Heterogeneous data allowed
•Null insertion possible
•Implements Serializable,Clonalbe
•Does not implement Randomaccess
•Link list is best choice – ?????
•Link list is Worst choice – ?????
•Link list is best choice – when frequent
operation is insertion or deletion in middle.
•Link list is Worst choice – when frequent
operation is retrieval .
Constructor
•LinkedList l1=new LinkedList();
–Creates an empty Linked Object
•LinkedList l1=new LinkedList(Collection c);
–Creates an equivalent LindkedList Object for given
collection
•LinkedList used to implement stacks and queues
to provide support for this requirement.
•Stack=> LIFO Queue=>FIFO
•LinkedList class defines the following methods:
void addFirst(); void addLast();
Object getFirst(); Object getLast();
Object removeFirst(); Object removeLast();
import java.util.*;
public class ListExample1{
public static void main(String args[]){
LinkedList l1=new LinkedList();
l .add("Ram");
l .add(2);
l .add("CSE");
l .set(0,"Ravi");
l .add(0,"Raj");
l .addFirst("MCET");
l .addLast(null);
System.out.println(l );
}
}
O/P ?
Vector
•Methods present in vector are synchronized.
Vector objects are always safe.
•Vector is a best choice when our frequent
operations is retrieval
Names?

Vector-1995

ArrayList
Vector Constructor
• Vector v= new Vector();
–create an empty vector with 10 initial capacity
–Capacity increased by newcapacity= 2* Current capacity

• Vector v=new Vector (int initialcapacity);


–Creates empty vector with sepecifed capacicty

• Vector v=new Vector (int initialcapacity, int increment


capacity);
–Vector v=new Vector(100,10)

• Vector v= new Vector(Collection c)


–Creates an equivalent Vector object for given collection object
Vector
•Adding Object: addElement(Object O)
•Removing Objects
removeElement(Object o)
removeElementAt(int index)
removeAllElements()
Vector
•For Accessing Elements
–ObjectelementAt(int index)
–Object firstElement()
–Object lastElement()
Other Methods:
int size();
int capacity();
Enumenration elements();
import java.util.*;
public class ListExample1{
public static void main(String args[]){
Vector v=new Vector();
System.out.println(v.capacity());
for(int i=1;i<=10; i++)
{
v.addElement(i);
}
System.out.println(v.capacity());
v.addElement(11);
System.out.println(v.capacity());
}
}
O/P ->?
Stack
•Stack is child class of vector
•It is specially designed for LIFO

Constructor
•Stack objectname=new Stack();
Stack
Methods
• Object Push(Object o)-for inserting objects in to stack
• Object pop()-remove and returns top of the stack
• Object peek()-returns the top of the stack without
removel of object
• emtpy()-return true when stack empty .
• int search(Object)-search specified value and return
offset .
–offset-From the top of the stack position of search
element.
Stack-example
import java.util.*;
class StackDemo
{
public static void main(String arg[]){
Stack s=new Stack();
s.push("ECE");
s.push("EEE");
s.push("CSE"); [ECE,EEE,CSE]

System.out.println(s); 1
System.out.println(s.search("CSE"));
System.out.println(s.search("IT")); -1

}
}
Queue
•Java Queue interface orders the element in
FIFO(First In First Out) manner.
•In FIFO, first element is removed first and last
element is removed at last.
Queue
Method Description

boolean add(object) It is used to insert the specified element


into this queue and return true upon
success.
Object remove() It is used to retrieves and removes the
head of this queue.
Object poll() It is used to retrieves and removes the
head of this queue, or returns null if this
queue is empty.
Object element() It is used to retrieves, but does not
remove, the head of this queue.
Object peek() It is used to retrieves, but does not
remove, the head of this queue, or
returns null if this queue is empty.
Queue
PriorityQueue class
•The PriorityQueue class provides the facility of
using queue. But it does not orders the
elements in FIFO manner.
•It inherits AbstractQueue class
•public class PriorityQueue<E> extends Abstrac
tQueue<E> implements Serializable
•.
Queue
import java.util.*;
class myqueue{
public static void main(String args[]){
PriorityQueue queue=new PriorityQueue ();
queue.add("Amit");
queue.add("Vijay");
queue.add("Karan");
queue.add("Jai");
queue.add("Rahul");
System.out.println("head:"+queue.element());
System.out.println("head:"+queue.peek());
}}
ArrayList Vector
1) ArrayList is not synchronized. Vector is synchronized.
2) ArrayList increments 50% of Vector increments 100% means
current array size if number of doubles the array size if total number
element exceeds from its of element exceeds than its capacity.
capacity.
3) ArrayList is not a legacy class, Vector is a legacy class.
it is introduced in JDK 1.2.
4) ArrayList is fast because it is Vector is slow because it is
non-synchronized. synchronized i.e. in multithreading
environment, it will hold the other
threads in runnable or non-runnable
state until current thread releases the
lock of object.
5)ArrayList uses Iterator Vector uses Enumeration interface to
interface to traverse the traverse the elements. But it can use
elements. Iterator also.
ArrayList LinkedList

1) ArrayList internally uses dynamic LinkedList internally uses doubly


array to store the elements. linked list to store the elements.

2) Manipulation with ArrayList Manipulation with LinkedList


is slow because it internally uses is faster than ArrayList because it
array. If any element is removed uses doubly linked list so no bit
from the array, all the bits are shifting is required in memory.
shifted in memory.

3) ArrayList class can act as a LinkedList class can act as a list


list only because it implements List and queue both because it
only. implements List and Deque
interfaces.

4) ArrayList is better for storing and LinkedList is better for


accessing data. manipulating data.

5)\ArrayList implements LinkedList doesnot implements


Cursor

•Cursor helps to retrieve objects one by one


from the collection .
•There are three types of cursors:
–Enumeration
–Iterator
–ListIterator
Enumeration
•Introduced in 1.0 version
•Enumeration to get objects one by one from the old
collection objects (vector)
•Enumeration object cane be created using elements of
vector class.
–public Enumerations elements();
Vector
–Example
•Enumeration e=v.elements();
•Methods
–public boolean hasmoreElement()
–public Object nextElement();
Enumeration
import java.util.*;
class EnumDemo
{
public static void main(String arg[]){
Vector v = new Vector();
for(int i=0;i<10;i++)
v.addElement(i);
System.out.println(v);
Enumeration e=v.elements();
while(e.hasMoreElements())
{
System.out.println((Integer)e.nextElement());
}
System.out.println(v);
}
}
Iterator
•Iterator is called Universal Cursor, because it used
for any collection objects.
•It can perform both read remove operations
•public Iterator iterator()
•Eg: Iterator itr=c.iterator();
•Methods
–public boolean hasnext();
–public Object next();
–public void remove();
import java.util.*;
class StackDemo
Iterator
{
public static void main(String arg[]){
ArrayList l=new ArrayList();
for(int i=0;i<10;i++)
l.add(i);
System.out.println(l);
Iterator itr=l.iterator();
while(itr.hasNext())
{
Integer I=(Integer)itr.next();
if(I%2!=0) itr.remove();
}
System.out.println(l);
Limitations
•Only Forward direction
•Read and Remove operations in iterator. but
replace and addition not possible.
ListIterator(I)
•We can move either forward or backward
direction
•Thus it is a Bidirectional cursor
•It can perform replacement , addition
operation, read operation and remove
•public ListIterator listIterator()
•Eg:
–ListIterator itr=l.listIterator(); I is list object
•It is a child interface of Iterator thus all
the methods in iterator by default available here
•It contains 9 methods
Forward Direction
public boolean Other methods
hasNext() public void remove()
Public void next() public void set(Object
Public int nextIndex() new)
Backward direction public void add(Object
new)
public boolean hasPreviopus()
Public void previous();
Public int previousIndex()
import java.util.*;
public class LIExample{
public static void main(String args[]){
LinkedList l=new LinkedList();
l.add("AAA");
l.add("bbb");
System.out.println(l);
ListIterator ltr=l.listIterator();
while(ltr.hasNext())
{
String s=(String)ltr.next();
if (s.equals("bbb"))
ltr.set("BBB");
}
System.out.println(l);
}
}
•ListIterator is a powerful cursor.
•But it is only applicable for List collection.
Property Enumeration Iterator ListIterator
Applicable for Only legacy class All collection Only list collection
class
Accessible Read only Both read and Read, replace,
remove remove and add
objects
How to get elements() iterator() Listiterator()metho
element? method of Vector method of d of List
Method name Collection
Movement Only Forward Both forward and
(Single direction ) backward
(bidirectional)
Methods hasMoreElement hasNext() hasNext(), next()
() next() nextIndex()
nextElement() remove() hasPreviopus()
previous();
previousIndex()
remove() ,set()
add()
Version 1.0V 1.2V 1.2V
String Tokenizer
•The java.util.StringTokenizer class allows you
to break a string into tokens. It is simple way
to break string.

75
String Tokenizer
•The String Tokenizer implements the process
of Lexical Analyser (lexer or scanner)
–Lexer – the first step in Parsing a String
–Parsing - is the division of text into a set of
discrete parts, or tokens, that conveys a semantic
meaning
•It uses “delimiters” to divide a string
–Delimiters are characters that separate tokens

76
Constructors
• StringTokenizer(String str)
–str - is the string that will be tokenized
–Default delimiters are used
• StringTokenizer(String str, String delimiters)
–str - is the string that will be tokenized
–Delimiters – Specified by the program
• StringTokenizer(String str, String delimiters, boolean
delimAsToken)
–str - is the string that will be tokenized
–Delimiters – Specified by the program
–delimAsToken – true: delimiters will also be tokenized.
77
Methods
–hasMoreTokens()-checks if there is more tokens
available.
–nextToken()- returns the next token from the
StringTokenizer object.
–nextToken(String delim)-returns the next token based
on the delimeter.
– countTokens()-returns the total number of tokens.

78
79
Date
•Used to retrieve the current Date and Time
from the system.
•2 constructors:
–Date()
•Retrieves the current date and time and returns as an
object.
–Date(long millisec)
•Argument  Number of milliseconds that have elapsed
since midnight, January 1, 1970

80
Methods...

81
82
Calendar
•Provides a set of methods that allows you to
convert a time in milliseconds to a number of
useful components
•Calendar provides no public constructors.
•get() returns value of components like
year,month,day

83
Methods...

84
Methods...

85
Methods...

86
87
Constants

88
Random
•The Random class is a generator of
pseudorandom numbers.
•2 constructors:
–Random()  uses current time as the starting
–Random(long seed)  uses seed as starting

89
Methods…

90
91
92
Currency

93
Currency

94

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy