You are on page 1of 44

Collection

• The Collection in Java is a framework that


provides an architecture to store and
manipulate the group of objects.
• A Collection represents a single unit of
objects, i.e., a group.
Collection hierarchy
Collection
• Iterator interface provides the facility of iterating
the elements in a forward direction only.
• List interface is the child interface of Collection
interface.
• List interface is implemented by the classes
ArrayList, LinkedList, Vector, and Stack.
Generics
• It deals with type-safe objects. It makes the code stable
by detecting the bugs at compile time.
• 1) Type-safety: We can hold only a single type of objects
in generics. It doesn’t allow to store other objects.
• List list = new ArrayList();
• list.add(10);
• list.add("10");

• List<Integer> list = new ArrayList<Integer>();


• list.add(10);
• list.add("10");// compile-time error
Generics
2) Type casting is not required: There is no need to
typecast the object.
List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0);//typecasting
After Generics, we don't need to typecast the
object.
List<String> list = new ArrayList<String>();
list.add("hello");
String s = list.get(0);
Generics
• 3) Compile-Time Checking: It is checked at
compile time so problem will not occur at
runtime.
• The good programming strategy says it is far
better to handle the problem at compile time
than runtime.

• List<String> list = new ArrayList<String>();


• list.add("hello");
• list.add(32);//Compile Time Error
ArrayList
• ArrayList class uses a dynamic array for storing the
elements. It is like an array, but there is no size limit.
• public class ArrayList<E> extends AbstractList<E> im
plements List<E>, RandomAccess, Cloneable, Seriali
zable  
• The ArrayList in Java can have the duplicate
elements also.
• It implements the List interface so we can use all the
methods of List interface here. The ArrayList
maintains the insertion order internally.
ArrayList
• Java ArrayList class is non synchronized.
• Java ArrayList allows random access because
array works at the index basis.
• In ArrayList, manipulation is little bit slower than
the LinkedList in Java because a lot of shifting
needs to occur if any element is removed from
the array list.
ArrayList
• ArrayList list=new ArrayList();//creating old non-
generic arraylist  
• ArrayList<String> list=new ArrayList<String>();//
creating new generic arraylist  
ArrayList example
import java.util.*;
public class ArrayListExample1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist

list.add(“Hi");//Adding object in arraylist


list.add(“Hello");
list.add(“Welcome");
list.add(“Java");
//Printing the arraylist object
System.out.println(list);
}
}
Traversing list through Iterator
import java.util.*;
public class ArrayListExample2{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add(“Hi");//Adding object in arraylist
list.add(“Hello");
list.add(“Welcome");
list.add(“Java");
//Traversing list through Iterator
Iterator itr=list.iterator();//getting the Iterator
while(itr.hasNext()){//check if iterator has the elements
System.out.println(itr.next());//printing the element and move to next
}
}
}
For each loop
import java.util.*;
public class ArrayListExample3{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add(“Hi");//Adding object in arraylist
list.add(“Hello");
list.add(“Welome");
list.add(“Java");
//Traversing list through for-each loop
for(String fruit:list)
System.out.println(fruit);

}
}
LinkedList
• Java LinkedList class uses a doubly linked list to
store the elements.
• public class LinkedList<E> extends AbstractSequenti
alList<E> implements List<E>, Deque<E>, Cloneable
, Serializable
• Java LinkedList class can contain duplicate
elements.
• Java LinkedList class maintains insertion order.
• Java LinkedList class is non synchronized.
• In Java LinkedList class, manipulation is fast because
no shifting needs to occur.
LinkedList example
import java.util.*;
public class LinkedList1{
public static void main(String args[]){

LinkedList<String> ll=new LinkedList<String>();


ll.add(“Hi");
ll.add(“Hello");
ll.add(“Welcome");
ll.add(“Java");
  ll.remove(“Hello");  
 ll.add(1, ”abc”); 
   ll.addFirst(“xyz");  
     ll.addLast(“stu");  

Iterator<String> itr=ll.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
ArrayList vs LinkedList
HashSet

• Java HashSet class is used to create a collection


that uses a hash table for storage. It inherits the
AbstractSet class and implements Set interface.
• HashSet stores the elements by using a
mechanism called hashing.
• HashSet contains unique elements only.
• HashSet allows null value.
• HashSet class is non synchronized.
• HashSet doesn't maintain the insertion order.
Here, elements are inserted on the basis of their
hashcode
Hashset
public class HashSet<E> extends AbstractSet<E> 
implements Set<E>, Cloneable, Serializable  

• HashSet is the best approach for search


operations.
• The initial default capacity of HashSet is 16,
and the load factor is 0.75.
Hashset example
import java.util.*;
class HashSet1{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet();
set.add("One");
set.add("Two");
set.add("Three");
set.add("Four");
set.add("Five");
set.add("Three");
Iterator<String> i=set.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}
LinkedHashSet
• Java LinkedHashSet class is a HashSet and Linked
list implementation of the set interface.
• public class LinkedHashSet<E> extends HashSet<E>
 implements Set<E>, Cloneable, Serializable  
• Java LinkedHashSet class contains unique elements
only like HashSet.
• Java LinkedHashSet class provides all optional set
operation and permits null elements.
• Java LinkedHashSet class is non synchronized.
• Java LinkedHashSet class maintains insertion order.
LinkedHashSet example
import java.util.*;
class LinkedHashSet1{
public static void main(String args[]){
//Creating HashSet and adding elements
LinkedHashSet<String> set=new LinkedHashSet();
set.add("One");
set.add("Two");
set.add("Three");
set.add("Four");
set.add("Five");
Iterator<String> i=set.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}
TreeSet
• Java TreeSet class implements the Set interface that uses
a tree for storage.
• public class TreeSet<E> extends AbstractSet<E> impleme
nts NavigableSet<E>, Cloneable, Serializable  
• Java TreeSet class contains unique elements only like
HashSet.
• Java TreeSet class access and retrieval times are quiet
fast.
• Java TreeSet class doesn't allow null element.
• Java TreeSet class is non synchronized.
• Java TreeSet class maintains ascending order.
TreeSet example
import java.util.*;
class TreeSet1{
public static void main(String args[]){
//Creating and adding elements
TreeSet<String> al=new TreeSet<String>();
al.add(“Hi");
al.add(“Hello");
al.add(“Welcome");
al.add(“java");
//Traversing elements
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
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.
• public class PriorityQueue<E> extends AbstractQu
eue<E> implements Serializable  
• The PriorityQueue class provides the facility of
using queue. But it does not orders the elements
in FIFO manner.
• It inherits AbstractQueue class.
import java.util.*;
class TestQueue {
public static void main(String args[]){
PriorityQueue<String> queue=new PriorityQueue<String>();
queue.add(“Hi");
queue.add(“Hello");
queue.add(“Welcome");
queue.add(“Java");
System.out.println("head:"+queue.element());
System.out.println("head:"+queue.peek());
System.out.println("iterating the queue elements:");
Iterator itr=queue.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
queue.remove();
queue.poll();
System.out.println("after removing two elements:");
Iterator<String> itr2=queue.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());
}
}
}
Deque
• Java Deque Interface is a linear collection that
supports element insertion and removal at both
ends. Deque is an acronym for "double ended
queue".
• public class ArrayDeque<E> extends AbstractColl
ection<E> implements Deque<E>, Cloneable, Ser
ializable  
Deque
• Unlike Queue, we can add or remove elements
from both sides.
• Null elements are not allowed in the ArrayDeque.
• ArrayDeque is not thread safe.
• ArrayDeque has no capacity restrictions.
• ArrayDeque is faster than LinkedList and Stack.
Deque example
import java.util.*;
public class ArrayDequeExample {
public static void main(String[] args) {
//Creating Deque and adding elements
Deque<String> deque = new ArrayDeque<String>();
deque.add(“Hi");
deque.add(“Hello");
deque.add(“Welcome");
//Traversing elements
for (String str : deque) {
System.out.println(str);
}
}
}
Map
• A map contains values on the basis of key, i.e. key
and value pair.
• Each key and value pair is known as an entry. A
Map contains unique keys.
• Entry is the subinterface of Map. So we will be
accessed it by Map.Entry name.
• It returns a collection-view of the map, whose
elements are of this class.
HashMap example
import java.util.*;
public class MapExample1 {
public static void main(String[] args) {
Map map=new HashMap();
//Adding elements to map
map.put(1,“Hi");
map.put(5,“Hello");
map.put(2,“Welcome");
map.put(6,“Java");
//Traversing Map
Set set=map.entrySet();//Converting to Set so that we can traverse
Iterator itr=set.iterator();
while(itr.hasNext()){
//Converting to Map.Entry so that we can get key and value separately
Map.Entry entry=(Map.Entry)itr.next();
System.out.println(entry.getKey()+" "+entry.getValue());
}
}
}
Map Example2
import java.util.*;
class MapExample2{
public static void main(String args[]){
Map<Integer,String> map=new HashMap<Integer,String>();
map.put(100,“Hi");
map.put(101,“Hello");
map.put(102,“welcome");
//Elements can traverse in any order
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
HashMap
• Java HashMap class implements the Map
interface which allows us to store key and value
pair, where keys should be unique.
• If you try to insert the duplicate key, it will
replace the element of the corresponding key. It
is easy to perform operations using the key index
like updation, deletion, etc. HashMap class is
found in the java.util package.
HashMap
• Java HashMap contains values based on the key.
• Java HashMap contains only unique keys.
• Java HashMap may have one null key and
multiple null values.
• Java HashMap is non synchronized.
• Java HashMap maintains no order.
• The initial default capacity of Java HashMap class
is 16 with a load factor of 0.75.
HashMap
• public class HashMap<K,V> extends
AbstractMap<K,V> implements Map<K,V>,
Cloneable, Serializable
• K: It is the type of keys maintained by this map.
• V: It is the type of mapped values.
HashMapExample
import java.util.*;
public class HashMapExample1{
public static void main(String args[]){
HashMap<Integer,String> map=new HashMap<Integer,String>();//Creating HashMap
map.put(1,"Mango"); //Put elements in Map
map.put(2,"Apple");
map.put(3,"Banana");
map.put(4,"Grapes");
map.put(3,"Banana");

System.out.println("Iterating Hashmap...");
for(Map.Entry m : map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
HashMap implementation
• HashMap  works on the principle of hashing, we
have put() and get() method for storing and retrieving object
from HashMap.
• When we pass both key and value to put() method to store
on HashMap, it uses key object hashcode() method to
calculate hashcode and them by applying hashing on that
hashcode it identifies bucket location for storing value
object.
• While retrieving it uses key object equals method to find out
correct key value pair and return value object associated
with that key.
• HashMap  uses linked list in case of collision and object will
be stored in next node of linked list.
LinkedHashMap
• Java LinkedHashMap class is Hashtable and Linked list
implementation of the Map interface.
• public class LinkedHashMap<K,V> extends HashMap<K,V> 
implements Map<K,V>  
Java LinkedHashMap contains values based on the key.
• Java LinkedHashMap contains unique elements.
• Java LinkedHashMap may have one null key and multiple
null values.
• Java LinkedHashMap is non synchronized.
• Java LinkedHashMap maintains insertion order.
• The initial default capacity of Java HashMap class is 16
with a load factor of 0.75.
LinkedHashMap example
import java.util.*;
class LinkedHashMap1{
public static void main(String args[]){

LinkedHashMap<Integer,String> hm=new LinkedHashMap<Integer,String>();

hm.put(100,“Hi");
hm.put(101,“Hello");
hm.put(102,“Welcome");

//Fetching key
System.out.println("Keys: "+map.keySet());
//Fetching value
System.out.println("Values: "+map.values());
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
TreeMap
• Java TreeMap class is a red-black tree based
implementation. It provides an efficient means of
storing key-value pairs in sorted order.
• Java TreeMap contains values based on the key. It
implements the NavigableMap interface and extends
AbstractMap class.
• Java TreeMap contains only unique elements.
• Java TreeMap cannot have a null key but can have
multiple null values.
• Java TreeMap is non synchronized.
• Java TreeMap maintains ascending order.
Tree Map
• public class TreeMap<K,V> extends AbstractMap<
K,V> implements NavigableMap<K,V>, Cloneable, 
Serializable  
TreeMap Example
import java.util.*;
class TreeMap1{
public static void main(String args[]){
TreeMap<Integer,String> map=new TreeMap<Integer,String>();
map.put(100,“hi");
map.put(102,“hello");
map.put(101,“welcome");
map.put(103,“java");

for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Hashtable
• It inherits Dictionary class and implements the
Map interface.
• Java Hashtable class contains unique elements.
• Java Hashtable class doesn't allow null key or
value.
• Java Hashtable class is synchronized.
• The initial default capacity of Hashtable class is 11
whereas loadFactor is 0.75.
Hashtable
• public class Hashtable<K,V> extends Dictionar
y<K,V> implements Map<K,V>, Cloneable, Seri
alizable  
Hashtable example
import java.util.*;
class Hashtable1{
public static void main(String args[]){
Hashtable<Integer,String> hm=new Hashtable<Integer,String>();

hm.put(100,“hi");
hm.put(102,“hello");
hm.put(101,“welcome");
hm.put(103,“java");

for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
HashMap Vs Hashtable

You might also like