[go: up one dir, main page]

0% found this document useful (0 votes)
5 views44 pages

Collection FrameWork-2

Advance Java Concepts

Uploaded by

saritha
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)
5 views44 pages

Collection FrameWork-2

Advance Java Concepts

Uploaded by

saritha
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/ 44

Collection

Set

HashSet SortedSet

TreeSet
Hash Set
• The underlying data Structure is Hash Table.
• Duplicate values are not allowed .If we insert duplicate
values we don’t get any compile time or run time error,
add() returns false.
• Insertion order is not preserved and all objects are inserted
based on hash-code of objects.
• Heterogenous objects are allowed.
• “null” insertion is possible.
• It is best suitable for Search Operation.
Constructors of HashSet
• HashSet h=new HashSet();
Creates an empty HashSet object with default initial capacity 16.
and default fill ratio=0.75.
• HashSet h=new HashSet(int initialcapacity);
Creates an empty HashSet object with Specified initial capacity
and default fill ratio=0.75.
• HashSet h=new HashSet(int initialcapacity,float loadfactor);
Creates an empty HashSet object with Specified initial capacity
and specified loadfactor(fill ratio).
HashSet h=new HashSet(Collection c);
For inter conversion between collection Objects.
• Load Factor
After Loading the how much factor, a new HashSet Object will be
created that factor is called as Load Factor or Fill Factor

For Example:
If we consider an ArrayList Object then
ArrayList a=new ArrayList()- by default load factor is 0.5
• Example
import java.util.*;
Class HashSetDemo
{
psvm(String s[])
{
HashSet h=new HashSet();
h.add(“B”);
h.add(“D”);
h.add(“Z”);
h.add(null);
h.add(10);
s.o.pln(“Elements of HashSet”+h)
s.o.pln(h.add(“Z”));}}
• Other utility methods
• The HashSet class has the following methods to work with elements of it.
• int size( ) - Returns the total number of elements in the invoking HashSet.
• boolean isEmpty( ) - Returns true if the HashSet is empty otherwise returns false.
• HashSet clone( ) - Returns a copy of the invoking HashSet.
• boolean contains(Object element) - Returns true if the HashSet contains given element
otherwise returns false.
• boolean containsAll(Collection c) - Returns true if the HashSet contains given collection of
elements otherwise returns false.
• boolean equals(Object o) - Compares the specified object with invoking HashSet collection for
equality.
• int hashCode( ) - Returns the hash code of the invoking HashSet.
• Object[ ] toArray( ) - Returns an array of Object instances that contains all the elements from
invoking HashSet.
• Spliterator spliterator( ) - Creates spliterator over the elements in a HashSet.
• Iterator iterator( ) - Returns an iterator over the elements in the HashSet. The iterator does not
return the elements in any particular order.
• The HashSet class has the following methods to remove items.
• boolean remove(Object o) - Removes the specified element from the
invoking HashSet.
• boolean removeAll(Collection c) - Removes all the elements of
specified collection from the invoking HashSet.
• boolean removeIf(Predicate p) - Removes all of the elements of
HashSet collection that satisfy the given predicate.
• boolean retainAll(Collection c) - Removes all of the elements of
HashSet collection except specified collection of elements.
• void clear( ) - Removes all the elements from the HashSet.
Import java.util.*;
public class HashSetExample1 {

public static void main(String[] args) {

HashSet set = new HashSet();


HashSet anotherSet = new HashSet();

set.add(10);
set.add(20);
set.add(30);
set.add(40);
set.add(50);
System.out.println("\nHashSet is\n" + set);
anotherSet.addAll(set);

}
System.out.println("\nanotherSet is\n" + anotherSet);

set.remove(20);
System.out.println("\nHashSet after remove(20) is\n" + set);

anotherSet.removeAll(set);
System.out.println("\nanotherSet after removeAll(set) is\n" + anotherSet);

set.retainAll(anotherSet);
System.out.println("\nset after retainAll(anotherSet) is\n" + set);

anotherSet.clear();
System.out.println("\nanotherSet after clear() is\n" + anotherSet);

}
SortedSet
• It is the child interface of set.
• 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.

For Example
{1,2,3}
{2,3,1} All the sets are equal but we cannot say which is the 1st or last.
{3,1,2}
For this these elements need tobe sorted.
SortedSet Specific Methods
Example Set: {100,101,103,104,107,110,115}
Object first()-returns first element of the SortedSet. 100
Object last()-returns last element of the SortedSet. 115
SortedSet headset(Object obj)-returns the SortedSet whose elements
are less than obj.
Ex:headSet(104)—[100,101,103]
SortedSet tailSet(Object obj)- returns the SortedSet whose elements
are greater than or equal obj.
Ex:tailSet(104)—[104,107,110,115]
SortedSet subSet(Object obj1,Object obj2)-returns the SortedSet
whose elements are >=obj1 and< obj2.
Ex:subSet(103,110)—[103,104,107]
Comparator comparator()-returns Comparator object that describes
underlying technique.If we are using default sorting order then
we will get null.
default sorting order---numbers Ascending Order
--- Strings Alphabetical order.
TreeSet
• The underlying datastructure for TreeSet is Balanced Tree.
• Duplicate objects are not allowed.
• Insertion order is not preserved,but all objects will be
inserted according to some sorting order.
• Heterogenous objects are not allowed.
• Null Insrtion is allowed but only once.
Constructors of TreeSet
TreeSet t=new TreeSet();
creates an empty TreeSet object where elements will be inserted
according default natural sorting order.
TreeSet t=new TreeSet(Comparator c);
Creates an empty TreeSet Object where elements will be
inserted according to customized sorting order
TreeSet t=new TreeSet(SortedSet s);
Creates TreeSet on SortedSet of elements.
TreeSet t=new TreeSet(Collection C);
Converts any collection object to TreeSet.
Import java.util.*;
class TreeSetDemo {
psvm(String s[]) {
TreeSet t=new TreeSet();
t.add(“A”);
t.add(“a”);
t.add(“B”);
t.add(“Z”);
t.add(“L”);
t.add(new Integer(10));
t.add(null);
System.out.println(t);
}}
Note:
• Null can be inserted as the first element,but after inserting null if we
try to insert any other element we will get NullPointerException
For example:TreeSet t=new TreeSet();
t.add(null);
t.add(“a”);
For Non empty TreeSet if we are trying to insert Null then we will get
NullPointerException.
For example:TreeSet t=new TreeSet();
A
t.add(“a”);
t.add(null);
null
PriorityQueue

• Underlying datastructure for PriorityQueue is Queue,in which objects


are processed(added) based on their priority.
• By default Priority is determined by objects natural ordering.
• It donot follow queue’s FIFO Strategy.
• Default initial Capacity of PriorityQueue is 11.
• Head of the PriorityQueue is least element based on natural ordering
or comparator based ordering.
Constructors of PriorityQueue
• PriorityQueue p=new PriorityQueue();
creates empty queue with default initial capacity(11),
and orders its elements according to their natural
ordering.
• PriorityQueue p=new PriorityQueue(int initialcapacity);
creates empty queue with specified initial capacity,
and orders its elements according to their natural
ordering.
• PriorityQueue p=new PriorityQueue(int initialcapacity,Comparator c);
creates empty queue with specified initial capacity,
and orders its elements according to their specified comparator.

• PriorityQueue p=new PriorityQueue(SortedSet s);


creates empty queue containing the elements in specified sorted
Set
Methods
• boolean offer(object)-inserts specified element into priority queue.
• boolean add(object)-inserts specified element into priority queue
• Object poll()-retrieves and removes the head of this queue or returns
null if this queue is empty.
• Object element()-retrieves the head of this queue or returns
NoSuchElementException if this queue is empty.
• bject peek()-retrieves the head of this queue or returns null if this
queue is empty.
• boolean remove()-removes single instance of element if it is present.
• void clear()-removes all the elements from the queue.
• boolean contains(Object o)-returns true if the queue contains the
specified element.
import java.util.*;
class PriorityQueueDemo {
public static void main(String s[]){
PriorityQueue p=new PriorityQueue();
p.add(750);
p.add(500);
p.add(900);
p.add(100);
System.out.println(p);
p.remove();
p.offer(1000);
System.out.println(p.peek());
System.out.println(p);
System.out.println(p.contains(100));
}}
Iterator
• Iterator is an interface which belongs to Collection Framework.
• It allows us to traverse the collection,access the data element
and remove the data elements of the collection.
• Java.util package has iterator interface.
public interface Iterator
• Syntax of Iterator object
Iterator it=c.iterator(); where iterator is public method of Iterator
interface and “c” is object of any collection class.

10 20 5 15 10

Consider an ArrayList
 ArrayList a=new ArrayList()----- “a” is the object of ArrayList class.
 Iterator i=a.iterator----stmt is used to traverse through ArrayList
Collection
Iterator supports 3 methods
• boolean hasNext()-returns true if iterator has more elements to
iterate.
• Object next():returns the next element in the collection until the
hasNext() method return true.This method throws “NoSuchElement
Exception if there is no next element.
• Void remove():removes the current element in the collection,this
method throws IllegalStateException if this function is called before
next() is invoked.
Example
import java.util.*;
class IteratorDemo {
public static void main(String s[]){
ArrayList a=new ArrayList();
a.add(10);
a.add(30);
a.add(50);
a.add(40);
a.add(20);
Iterator i=a.iterator();
System.out.println("Elements of ArrayList are:");
while(i.hasNext())
System.out.println(i.next()+" ");
}}
import java.util.*;
class IteratorDemo1 {
public static void main(String s[]) {
ArrayList a=new ArrayList();
for(int i=0;i<=10;i++)
a.add(i);
System.out.println(a);
Iterator i= a.iterator();
while(i.hasNext()) {
Integer I=(Integer)i.next();
if(I%2==0)
System.out.println(I);
else
i.remove(); }
System.out.println(a);
} }
Limitations of Iterator
 can used to Access only in forward direction.
 We can perform read or remove operations but we can’t
perform replacement of new objects.

Note: to overcome above limitations we use ListIterator.


ListIterator
• ListIterator is the child interface of Iterator.
Iterator

ListIterator
• ListIterator we can move either to the forward direction or to
the backward direction and hence ListIterator is
bidirectional.
• Along with read and remove operation we can perform
replacement and addition of new objects.
We can create ListIterator Object by using listIterator()
method of List Interface.
public ListIterator listIterator()
Example
ListIterator li=l.listIterator();
where l is any List object.
Methods:
• ListIterator is the child interface of Iterator and all the
methods of iterator by default available to ListIterator.
• It defines the following nine methods
• To access elements in forward direction the methods are
public Boolean hasNext()
public void next()
public int nextIndex()
• To access elements in backward direction the methods are
public Boolean hasPrevious()
public void previous()
public int PreviousIndex()
• Other Methods
public void remove()
public void set(Object new)
public void add(Object new)
import java.util.*;
class ListIteratorDemo {
public static void main(String args[]) {
LinkedList l=new LinkedList();
l.add("a");
l.add("c");
l.add("z");
l.add("k");
System.out.println(l);
ListIterator lt=l.listIterator();
while(lt.hasNext()) {
String s=(String)lt.next();
if(s.equals("c"))
lt.remove();
else if(s.equals("z"))
lt.add("m");
else if(s.equals("k"))
lt.set("y"); }
For Each Alternative
• It is enhanced for loop.
• This concept is introduced from java1.5 version
• It is used to process the elements of array or Collections.
• We can iterate elements without bounds.
• It access elements from first index to last index.
• For each loop process elements one by one only in forward direction.
Syntax:
for(data_type variable:array|collection)
{
//body of foreach loop
}
import java.util.*;
class ForEachDemo
{
public static void main(String args[])
{
ArrayList<Integer> a=new ArrayList<Integer> ();
a.add(10);
a.add(20);
a.add(30);
a.add(40);
System.out.println(“Array elements are”);
for(Integer s:a)
System.out.println(s);
}}
Map Interface and Classes
Map

HashMap SortedMap Hashtable

LinkedHashMap NavigatableMap Properties

TreeMap
Map Interface and Classes
• Map is not a child Interface of Collection.
• If you want to represent a group of objects as Key-Value pair then we
use Map.
Ex: Key Value
101 sachin
102 rakesh
103 sriram
104 Sachin

• Both the Key-Value pair are object type.


• Each Key-Value pair is called Entry.Hence Map is considered as a
collection of Entry object.
• Duplicate Keys are not allowed,but values may be duplicated.
Map Interface Specific Methods
• Object put(Object key,Object value)-inserts one key-value pair to the
Map.
Ex: m.put(101,”raju”); returns null as key is not already
m.put(102,”rduplictani”); present in the Map.
m.put(102,”kiran”);--this insertion returns old value “Rani” as it
is a duplicate value
• Void putAll(Map m)-inserts more than one key-value pair into Map.
• Object get(Object key)-returns the value associated with specified key.
• Object remove(Object key)-removes the entry associated with specified
key.
• boolean containsKey(Object key)-returns true if the specified key is
present.
• boolean containsValue(Object value)- returns true if the specified
value is present.
• boolean isEmpty()-returns true if the Map is empty.
• Set KeySet()-returns the all the key entries of the Map.
• Collection valueSet()-returns the all the value entries of the Map.
• int size()-returns the number of entries.
• void clear()-used to clear the contents of Map.
HashMap
• The underlying datastructure is Hash Table.
• Insertion order is not preserved and insertion is based on hash code
of keys.
• Duplicate keys are not allowed but values may be duplicated.
• Heterogeneous keys are allowed.
• Null is allowed for keys only once, but for value null can be declared
more than once.
• It is best suitable for search operation.
Constructors of HashMap
HashMap m=new HashMap()-creates an empty HashMap with default
initial capacity 16 and fill ratio 0.75.
HashMap m=new HashMap(int initialcapacity)-creates an empty
HashMap with specified initial capacity and fill ratio 0.75.
HashMap m=new HashMap(int initialcapacity,float loadfactor)-
creates an empty HashMap with specified initial capacity and fill
ratio.
HashMap m=new HashMap(Map m)-converts any collection into
HashMap.
import java.util.*;
class HashMapDemo
{
public static void main(String args[])
{
HashMap m=new HashMap();
m.put("Ramu",75);
m.put("Somu",70);
m.put("seeta",55);
m.put("laxman",45);
m.put("uma",95);
System.out.println(m);
System.out.println(m.put("seeta",80));
Set s=m.keySet();
System.out.println(s);
Collection c=m.values();
System.out.println(c);
Set s1=m.entrySet();
System.out.println(s1);
}
}
Hashtable
• The underlying datastructure is Hash Table.
• Insertion order is not preserved and insertion is based on hash code
of keys.
• Duplicate keys are not allowed but values may be duplicated.
• Heterogeneous keys are allowed.
• Null is allowed for keys only once, but for value null can be declared
more than once.
• It is the concrete implementation of Dictionary class and implements
Map interface.
Constructors of Hashtable
Hashtable m=new Hashtable()-creates an empty Hashtable with default
initial capacity.
Hashtable m=new Hashtable(int size)-creates an empty
Hashtable with specified initial capacity
Hashtable m=new Hashtable(int size,float fillfactor)-
creates an empty Hashtable with specified initial capacity and fill
ratio.
import java.util.*;
class HashtableDemo {
public static void main(String args[]) {
Hashtable<String,Integer> m=new Hashtable<String,Integer>();
m.put("Ramu",75);
m.put("Somu",70);
m.put("seeta",55);
m.put("laxman",45);
m.put("uma",95);
System.out.println(m);
for(Map.Entry m1:m.entrySet())
{
System.out.println(m1.getKey()+" "+m1.getValue());
} } }
Hashtable HashMap
Hashtable is synchronized HashMap is not synchronized

It is thread-safe. It means be It is not thread-safe. It means it


shared by multiple threads cannot shared by multiple threads.
It is slow It is fast

It is traversed by iterator and It is traversed by iterator.


enumerator
It is derived from dictionary class It is derived from AbstractMap

You might also like