0% found this document useful (0 votes)
26 views21 pages

Java Collection Framework Overview

The document discusses the Java Collection Framework which provides a unified architecture for storing and manipulating groups of objects. It includes interfaces like Set, List, Queue, Deque and classes like ArrayList, LinkedList, HashSet, TreeSet. The framework contains commonly used methods on the Collection interface like add(), remove(), size(). It also discusses the Iterator interface for iterating over elements and classes like ArrayList, LinkedList, HashSet and LinkedHashSet.

Uploaded by

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

Java Collection Framework Overview

The document discusses the Java Collection Framework which provides a unified architecture for storing and manipulating groups of objects. It includes interfaces like Set, List, Queue, Deque and classes like ArrayList, LinkedList, HashSet, TreeSet. The framework contains commonly used methods on the Collection interface like add(), remove(), size(). It also discusses the Iterator interface for iterating over elements and classes like ArrayList, LinkedList, HashSet and LinkedHashSet.

Uploaded by

manohar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java Collection Framework

1. Collection Framework
2. Hierarchy of Collection Framework
3. Methods of Collection interface
4. Iterator interface

Collection Framework provides an architecture to store and manipulate the group of objects.
All the operations that you perform on a data such as searching, sorting, insertion, deletion etc.
can be performed by Java Collection Framework.

Collection simply means a single unit of objects. Collection framework provides many interfaces
(Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList, PriorityQueue,
HashSet, LinkedHashSet, TreeSet etc).

What is Collection>

Collection represents a single unit of objects i.e. a group.

What is framework?

 provides readymade architecture.


 represents set of classes and interface.
 is optional.

Collection framework

Collection framework represents a unified architecture for storing and manipulating group of
object. It has:

1. Interfaces and its implementations i.e. classes


2. Algorithm

Do You Know ?
 What are the two ways to iterate the elements of a collection ?
 What is the difference between ArrayList and LinkedList classes in collection
framework ?
 What is the difference between ArrayList and Vector classes in collection framework ?
 What is the difference between HashSet and HashMap classes in collection framework ?
 What is the difference between HashMap and Hashtable class ?
 What is the difference between Iterator and Enumeration interface in collection
framework ?
 How can we sort the elements of an object. What is the difference between Comparable
and Comparator interfaces ?
 What does the hashcode() method ?

Hierarchy of Collection Framework

Let us see the hierarchy of collection [Link] [Link] package contains all the classes
and interfaces for Collection framework.

Commonly used methods of Collection interface

There are many methods declared in the Collection interface. They are as follows:

Method Description
public boolean add(object
is used to insert an element in this collection.
element)
public boolean addAll(collection is used to insert the specified collection elements in the
c) invoking collection.
public boolean remove(object
is used to delete an element from this collection.
element)
public boolean is used to delete all the elements of specified collection from
removeAll(Collection c) the invoking collection.
public boolean is used to delete all the elements of invoking collection
retainAll(Collection c) 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
is used to search an element.
element)
public boolean
is used to search the specified collection in this collection.
containsAll(collection c)
public Iterator iterator() returns an iterator.

Iterator interface

Iterator interface provides the facility of iterating the elements in forward direction only.

Methods of Iterator interface

There are only three methods in the Iterator interface. They are:
1. public boolean hasNext() it returns true if iterator has more elements.
2. public object next() it returns the element and moves the cursor pointer to the next
element.
3. public void remove() it removes the last elements returned by the iterator. It is rarely
used.

What we will learn in Collection Framework ?


 ArrayList class
 LinkedList class
 ListIterator interface
 HashSet class
 LinkedHashSet class
 TreeSet class
 PriorityQueue class
 Map interface
 HashMap class
 LinkedHashMap class
 TreeMap class
 Hashtable class
 Sorting
 Comparable interface
 Comparator interface

Difference between List and Set:


List can contain duplicate elements whereas Set contains unique elements only.

HashSet class:

 uses hashtable to store the [Link] extends AbstractSet class and implements Set interface.
 contains unique elements only.

Hierarchy of HashSet class:

Example of HashSet class:

1. import [Link].*;  
2. class Simple{  
3.  public static void main(String args[]){  
4.    
5.   HashSet al=new HashSet();  
6.   [Link]("Ravi");  
7.   [Link]("Vijay");  
8.   [Link]("Ravi");  
9.   [Link]("Ajay");  
10.   
11.   Iterator itr=[Link]();  
12.   while([Link]()){  
13.    [Link]([Link]());  
14.   }  
15.  }  
16. }  

Output:Ajay
Vijay
Ravi

LinkedHashSet class:
 contains unique elements only like HashSet. It extends HashSet class and implements Set
interface.
 maintains insertion order.

Hierarchy of LinkedHashSet class:


Example of LinkedHashSet class:

1. import [Link].*;  
2. class Simple{  
3.  public static void main(String args[]){  
4.    
5.   LinkedHashSet al=new LinkedHashSet();  
6.   [Link]("Ravi");  
7.   [Link]("Vijay");  
8.   [Link]("Ravi");  
9.   [Link]("Ajay");  
10.   
11.   Iterator itr=[Link]();  
12.   while([Link]()){  
13.    [Link]([Link]());  
14.   }  
15.  }  
16. }  
Output:>Ravi
Vijay
Ajay

List Interface:
List Interface is the subinterface of [Link] contains methods to insert and delete elements
in index [Link] is a factory of ListIterator interface.

Commonly used mehtods of List Interface:

1. public void add(int index,Object element);


2. public boolean addAll(int index,Collection c);
3. public object get(int Index position);
4. public object set(int index,Object element);
5. public object remove(int index);
6. public ListIterator listIterator();
7. public ListIterator listIterator(int i);

ListIterator Interface:

ListIterator Interface is used to traverse the element in backward and forward direction.

Commonly used mehtods of ListIterator Interface:

1. public boolean hasNext();


2. public Object next();
3. public boolean hasPrevious();
4. public Object previous();

Example of ListIterator Interface:

import [Link].*;  
class Simple5{  
public static void main(String args[]){  
  
ArrayList al=new ArrayList();  
[Link]("Amit");  
[Link]("Vijay");  
[Link]("Kumar");  
[Link](1,"Sachin");  
  
[Link]("element at 2nd position: "+[Link](2));  
  
ListIterator itr=[Link]();  
  
[Link]("traversing elements in forward direction...");  
while([Link]()){  
[Link]([Link]());  
 }  
  
  
[Link]("traversing elements in backward direction...");  
while([Link]()){  
[Link]([Link]());  
 }  
}  
}  
Output:element at 2nd position: Vijay
traversing elements in forward direction...
Amit
Sachin
Vijay
Kumar
traversing elements in backward direction...
Kumar
Vijay
Sachin
Amit

Difference between List and Set:


List can contain duplicate elements whereas Set contains unique elements only.

HashSet class:

 uses hashtable to store the [Link] extends AbstractSet class and implements Set interface.
 contains unique elements only.
Hierarchy of HashSet class:

Example of HashSet class:

1. import [Link].*;  
2. class Simple{  
3.  public static void main(String args[]){  
4.    
5.   HashSet al=new HashSet();  
6.   [Link]("Ravi");  
7.   [Link]("Vijay");  
8.   [Link]("Ravi");  
9.   [Link]("Ajay");  
10.   
11.   Iterator itr=[Link]();  
12.   while([Link]()){  
13.    [Link]([Link]());  
14.   }  
15.  }  
16. }  

Output:Ajay
Vijay
Ravi
LinkedHashSet class:
 contains unique elements only like HashSet. It extends HashSet class and implements Set
interface.
 maintains insertion order.

Hierarchy of LinkedHashSet class:

Example of LinkedHashSet class:

1. import [Link].*;  
2. class Simple{  
3.  public static void main(String args[]){  
4.    
5.   LinkedHashSet al=new LinkedHashSet();  
6.   [Link]("Ravi");  
7.   [Link]("Vijay");  
8.   [Link]("Ravi");  
9.   [Link]("Ajay");  
10.   
11.   Iterator itr=[Link]();  
12.   while([Link]()){  
13.    [Link]([Link]());  
14.   }  
15.  }  
16. }  

Output:>Ravi
Vijay
Ajay

ArrayList class:
 uses a dynamic array for storing the [Link] extends AbstractList class and implements List
interface.
 can contain duplicate elements.
 maintains insertion order.
 not synchronized.
 random access because array works at the index basis.
 manipulation slow because a lot of shifting needs to be occured.
Hierarchy of ArrayList class:

Example of ArrayList:

1. import [Link].*;  
2. class Simple{  
3.  public static void main(String args[]){  
4.    
5.   ArrayList al=new ArrayList();  
6.   [Link]("Ravi");  
7.   [Link]("Vijay");  
8.   [Link]("Ravi");  
9.   [Link]("Ajay");  
10.   
11.   Iterator itr=[Link]();  
12.   while([Link]()){  
13.    [Link]([Link]());  
14.   }  
15.  }  
16. }  

Output:Ravi
Vijay
Ravi
Ajay

Two ways to iterate the elements of collection:

1. By Iterator interface.
2. By for-each loop.

Iterating the elements of Collection by for-each loop:

1. import [Link].*;  
2. class Simple{  
3.  public static void main(String args[]){  
4.    
5.   ArrayList al=new ArrayList();  
6.   [Link]("Ravi");  
7.   [Link]("Vijay");  
8.   [Link]("Ravi");  
9.   [Link]("Ajay");  
10.   
11.   for(Object obj:al)  
12.     [Link](obj);  
13.  }  
14. }  

Output:Ravi
Vijay
Ravi
Ajay

Storing user-defined class objects:

class Student{  
  int rollno;  
  String name;  
  int age;  
  Student(int rollno,String name,int age){  
   [Link]=rollno;  
   [Link]=name;  
   [Link]=age;  
  }  
}  
import [Link].*;  
class Simple{  
 public static void main(String args[]){  
    
  Student s1=new Student(101,"Sonoo",23);  
  Student s2=new Student(102,"Ravi",21);  
  Student s2=new Student(103,"Hanumat",25);  
      
  ArrayList al=new ArrayList();  
  [Link](s1);  
  [Link](s2);  
  [Link](s3);  
    
  Iterator itr=[Link]();  
  while([Link]()){  
    Student st=(Student)[Link]();  
    [Link]([Link]+" "+[Link]+" "+[Link]);  
  }  
 }  
}  
Output:101 Sonoo 23
102 Ravi 21
103 Hanumat 25

Example of addAll(Collection c) method:

1. import [Link].*;  
2. class Simple{  
3.  public static void main(String args[]){  
4.    
5.   ArrayList al=new ArrayList();  
6.   [Link]("Ravi");  
7.   [Link]("Vijay");  
8.   [Link]("Ajay");  
9.     
10.   ArrayList al2=new ArrayList();  
11.   [Link]("Sonoo");  
12.   [Link]("Hanumat");  
13.     
14.   [Link](al2);    
15.   
16.   Iterator itr=[Link]();  
17.   while([Link]()){  
18.    [Link]([Link]());  
19.   }  
20.  }  
21. }  

Output:Ravi
Vijay
Ajay
Sonoo
Hanumat
Example of removeAll() method:

1. import [Link].*;  
2. class Simple{  
3.  public static void main(String args[]){  
4.    
5.   ArrayList al=new ArrayList();  
6.   [Link]("Ravi");  
7.   [Link]("Vijay");  
8.   [Link]("Ajay");  
9.     
10.   ArrayList al2=new ArrayList();  
11.   [Link]("Ravi");  
12.   [Link]("Hanumat");  
13.     
14.   [Link](al2);  
15.   
16.   [Link]("iterating the elements after removing the elements of al2...");  
17.   Iterator itr=[Link]();  
18.   while([Link]()){  
19.    [Link]([Link]());  
20.   }  
21.   
22.   }  
23. }  

Output:iterating the elements after removing the elements of al2...


Vijay
Ajay

Example of retainAll() method:

1. import [Link].*;  
2. class Simple{  
3.  public static void main(String args[]){  
4.    
5.   ArrayList al=new ArrayList();  
6.   [Link]("Ravi");  
7.   [Link]("Vijay");  
8.   [Link]("Ajay");  
9.     
10.   ArrayList al2=new ArrayList();  
11.   [Link]("Ravi");  
12.   [Link]("Hanumat");  
13.     
14.   [Link](al2);  
15.   
16.   [Link]("iterating the elements after retaining the elements of al2...");  
17.   Iterator itr=[Link]();  
18.   while([Link]()){  
19.    [Link]([Link]());  
20.   }  
21.  }  
22. }  

Output:iterating the elements after retaining the elements of al2...


Ravi

LinkedList class:
 uses doubly linked list to store the elements. It extends the AbstractList class and
implements List and Deque interfaces.
 can contain duplicate elements.
 maintains insertion order.
 not synchronized.
 No random access.
 manipulation fast because no shifting needs to be occured.
 can be used as list, stack or queue.

Example of LinkedList:

1. import [Link].*;  
2. class Simple{  
3.  public static void main(String args[]){  
4.    
5.   LinkedList al=new LinkedList();  
6.   [Link]("Ravi");  
7.   [Link]("Vijay");  
8.   [Link]("Ravi");  
9.   [Link]("Ajay");  
10.   
11.   Iterator itr=[Link]();  
12.   while([Link]()){  
13.    [Link]([Link]());  
14.   }  
15.  }  
16. }  

Output:Ravi
Vijay
Ravi
Ajay

Map Interface
A map contains values based on the key i.e. key and value [Link] pair is known as an
[Link] contains only unique elements.

Commonly used methods of Map interface:

1. public Object put(object key,Object value): is used to insert an entry in this map.
2. public void putAll(Map map):is used to insert the specifed map in this map.
3. public Object remove(object key):is used to delete an entry for the specified key.
4. public Object get(Object key):is used to return the value for the specified key.
5. public boolean containsKey(Object key):is used to search the specified key from this
map.
6. public boolean containsValue(Object value):is used to search the specified value from
this map.
7. public Set keySet():returns the Set view containing all the keys.
8. public Set entrySet():returns the Set view containing all the keys and values.

Entry

Entry is the subinterface of [Link] we will access it by [Link] [Link] provides methods to
get key and value.

Methods of Entry interface:

1. public Object getKey(): is used to obtain key.


2. public Object getValue():is used to obtain value.

HashMap class:
 A HashMap contains values based on the key. It implements the Map interface and extends
AbstractMap class.
 It contains only unique elements.
 It may have one null key and multiple null values.
 It maintains no order.

Hierarchy of HashMap class:

Example of HashMap class:

1. import [Link].*;  
2. class Simple{  
3.  public static void main(String args[]){  
4.    
5.   HashMap hm=new HashMap();  
6.   
7.   [Link](100,"Amit");  
8.   [Link](101,"Vijay");  
9.   [Link](102,"Rahul");  
10.   
11.   Set set=[Link]();  
12.   Iterator itr=[Link]();  
13.   
14.   while([Link]()){  
15.    [Link] m=([Link])[Link]();  
16.    [Link]([Link]()+" "+[Link]());  
17.   }  
18.  }  
19. }  

Output:102 Rahul
100 Amit
101 Vijay

What is difference between HashSet and HashMap?


HashSet contains only values whereas HashMap contains entry(key and value).

TreeMap class
 A TreeMap contains values based on the key. It implements the NavigableMap interface and
extends AbstractMap class.
 It contains only unique elements.
 It cannot have null key but can have multiple null values.
 It is same as HashMap instead maintains ascending order.

Hierarchy of TreeMap class:

Example of TreeMap class:

1. import [Link].*;  
2. class Simple{  
3.  public static void main(String args[]){  
4.    
5.   TreeMap hm=new TreeMap();  
6.   
7.   [Link](100,"Amit");  
8.   [Link](102,"Ravi");  
9.   [Link](101,"Vijay");  
10.   [Link](103,"Rahul");  
11.   
12.   Set set=[Link]();  
13.   Iterator itr=[Link]();  
14.   
15.   while([Link]()){  
16.    [Link] m=([Link])[Link]();  
17.    [Link]([Link]()+" "+[Link]());  
18.   }  
19.  }  
20. }  

Output:100 Amit
101 Vijay
102 Ravi
103 Rahul

What is difference between HashMap and TreeMap?

1) HashMap is can contain one null key. TreeMap connot contain any null key.

2) HashMap maintains no order. TreeMap maintains ascending order.

Next TopicHashtable Class In Collection Framework

Hashtable
 A Hashtable is an array of [Link] list is known as a [Link] position of bucket is
identified by calling the hashcode() method.A Hashtable contains values based on the
key. It implements the Map interface and extends Dictionary class.
 It contains only unique elements.
 It may have not have any null key or value.
 It is synchronized.

Example of Hashtable:

1. import [Link].*;  
2. class Simple{  
3.  public static void main(String args[]){  
4.    
5.   Hashtable hm=new Hashtable();  
6.   
7.   [Link](100,"Amit");  
8.   [Link](102,"Ravi");  
9.   [Link](101,"Vijay");  
10.   [Link](103,"Rahul");  
11.   
12.   Set set=[Link]();  
13.   Iterator itr=[Link]();  
14.   
15.   while([Link]()){  
16.    [Link] m=([Link])[Link]();  
17.    [Link]([Link]()+" "+[Link]());  
18.   }  
19.  }  
20. }  

Output:103 Rahul
102 Ravi
101 Vijay
100 Amit

What is difference between HashMap and Hashtable?

1) HashMap is not synchronized. Hashtable is synchronized.


2) HashMap can contain one null key and multiple Hashtable cannot contain any null key nor
null values. value.

Common questions

Powered by AI

The Iterator interface provides a way to traverse only in the forward direction and includes methods like hasNext(), next(), and remove() for basic iteration tasks . Meanwhile, the ListIterator interface is specifically for lists and offers more functionality, allowing traversal in both forward and backward directions with methods like hasNext(), hasPrevious(), next(), and previous(). ListIterator also allows addition, modification, and querying the position of elements, which Iterator does not support .

HashSet in Java is designed to store unique elements only and uses a hashtable for its operations . It does not maintain any order of its elements. On the other hand, HashMap stores data in pairs of keys and values, allowing unique keys but permitting multiple null values. Additionally, HashMap does not maintain any order of its entries and allows one null key . The key distinction lies in HashSet being a collection of distinct elements, whereas HashMap is a mapping of keys to values .

TreeMap in Java maintains its entries in ascending order according to their natural ordering or by a Comparator provided at map creation time . This is achieved by implementing the NavigableMap interface and utilizing Red-Black trees under the hood . This ordered structure is advantageous as it allows for efficient key-value pair retrieval in order, enabling in-order views of the keys and values, and supporting operations like firstKey(), lastKey(), and subMap(), which are not available with other Map implementations like HashMap .

The primary distinction between Comparable and Comparator interfaces in Java is that the Comparable interface is used to define a natural ordering of objects, where a class implementing Comparable must define the compareTo method to determine order by a single attribute . In contrast, the Comparator interface is used for defining external comparison logic, allowing multiple ways to compare instances of a class by implementing the compare method, which is advantageous for sorting objects by different attributes without modifying their natural ordering .

The Java Collection Framework provides a unified architecture to store and manipulate a group of elements, offering flexibilities such as dynamic resizing, type safety with generics, and various algorithms for data manipulation including sorting and searching . In contrast, a standard array in Java has a fixed size and does not inherently provide many of the operations such as searching, sorting, insertion, and deletion without additional coding . Moreover, collections offer interfaces such as Set, List, and Queue which come with methods optimized for different data handling scenarios, whereas arrays only offer basic operations .

A Hashtable would be chosen over a HashMap in scenarios where thread safety is necessary because Hashtable is synchronized, which makes it thread-safe when concurrently accessed by multiple threads . In contrast, HashMap is unsynchronized, making it faster but prone to concurrent modification issues when used in multi-threaded environments without external synchronization. Additionally, Hashtable does not allow null keys or values, which can be beneficial for eliminating null-related errors in applications that handle only non-null data .

LinkedList offers various advantages over ArrayList within the Java Collection Framework. It uses a doubly linked list structure, which allows quick insertions and deletions without the need for resizing, unlike ArrayList which relies on a dynamic array, requiring reallocation and potentially costly shifts . LinkedLists do not support random access, making them preferable over ArrayLists when high volume insertions and deletions are needed at non-terminal positions. Furthermore, being a Deque, a LinkedList can also be efficiently used as a List, Queue, or a Deque .

The List interface in the Java Collection Framework enhances data handling over a basic array by providing a more flexible structure for handling collections of objects. Lists allow dynamic resizing, enabling them to grow and shrink as elements are added or removed . They support indexed access, offering methods for inserting, removing, and replacing elements at any position, which arrays do not natively support . This ability allows for more sophisticated data manipulation, such as maintaining insertion order, searching, and iterating in different ways using ListIterator, which are not possible with basic arrays where metadata about position and order must manually be tracked .

ArrayList and Vector both use dynamically resizable arrays to store elements. However, ArrayList is not synchronized, making it unsuitable for concurrent access from multiple threads but faster in single-threaded scenarios due to lack of overhead from synchronization . Vector, on the other hand, is synchronized, making it thread-safe but incurring a performance hit because of synchronization overhead. These differences imply that ArrayList is preferable in cases where performance is critical and thread-safety is not a concern, while Vector should be chosen when working in a multi-threaded environment where thread-safety is paramount .

HashSet and LinkedHashSet both store unique elements, but they differ in terms of element order and performance. HashSet does not maintain any order of the inserted elements, optimizing it for faster performance and thus, being ideal for scenarios where insertion order is irrelevant . LinkedHashSet, however, maintains the order in which elements are inserted, providing benefits in scenarios where the retrieval order matters . This maintenance of insertion order comes with a slight performance overhead compared to HashSet, due to the internal complexity needed to track this order .

You might also like