Unit IV Collections1
Unit IV Collections1
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
Collection Container
List
(1.2)
Stack
(1.2)
Legacy Classes
Collection Framework
3-Set
•It is the child interface of Collection
Set
(1.2)
HashSet
(1.2)
Linked HashSet
(1.4)
Collection Framework
4-SortedSet
•It is the child interface of Collection
Set
(1.2)
SortedSet
(1.2)
NaviableSet
(1.6)
TreeSet
(1.2)
Collection Framework
6-Queue
•It is the child interface of Collection
Queue
(1.5)
PriorityQueue
(1.5) BlockingQueue
(1.5)
A01 Raj
A02 Sam
A03 Ravi
Dictionary
(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.
List
(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
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
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
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