0% found this document useful (0 votes)
21 views15 pages

Java Collections Framework Overview

The document provides an overview of the Java Collections Framework, detailing its architecture for storing and manipulating groups of objects through various interfaces and classes such as Collection, List, Set, and their implementations like ArrayList, HashSet, and TreeSet. It explains the functionalities of these interfaces, including methods for adding, removing, and accessing elements, as well as the characteristics of each collection type. Additionally, it includes examples demonstrating the usage of these collections in Java programming.

Uploaded by

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

Java Collections Framework Overview

The document provides an overview of the Java Collections Framework, detailing its architecture for storing and manipulating groups of objects through various interfaces and classes such as Collection, List, Set, and their implementations like ArrayList, HashSet, and TreeSet. It explains the functionalities of these interfaces, including methods for adding, removing, and accessing elements, as well as the characteristics of each collection type. Additionally, it includes examples demonstrating the usage of these collections in Java programming.

Uploaded by

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

Collections Framework

Collections:
 Collection is a framework that provides architecture to store and manipulate the
group of objects.
 It can achieve all the operations that you perform on a data such as searching, sorting,
insertion, manipulation, and deletion.
 A Collection represents a single unit of objects, i.e., a group.
 Java Collection framework provides many interfaces (Collection, List, Set and Sorted
Set) and classes (Array List, HashSet, and TreeSet)
 It provides readymade architecture.

Collection Interfaces:
 Collection Interface
 List Interfae
 Set Interface
 Sorted Set Interface

Collection classes:
 Array List
 HashSet
 TreeSet

Hash Map Accessing a Collection via an Iterator:


.
Collection Interface

 The Collection interface is a member of the java collections framework


 It is a part of [Link] package.
 It is one of the root interfaces of the Collection Hierarchy.
 The Collection interface is not directly implemented by any class.
 The Collection interface is the interface which is implemented by all the classes in the
collection framework.

Here List, Set and Queue are sub interfaces of Collection interface.

The Collection interface includes various methods that can be used to perform different
operations on objects. These methods are available in all its sub interfaces.

add() - inserts the specified element to the collection


size() - returns the size of the collection
remove() - removes the specified element from the collection
iterator() - returns an iterator to access elements of the collection
addAll() - adds all the elements of a specified collection to the collection
removeAll() - removes all the elements of the specified collection from the collection
clear() - removes all the elements of the collection
etc…
.
Example:
import [Link].*;
import [Link].*;
public class CollectionDemo {
public static void main(String args[])
{
// creating an empty LinkedList
Collection<String> list = new LinkedList<String>();

// use add() method to add elements in the list


[Link]("One");
[Link]("Two");
[Link]("Three");

// Output the present list


[Link]("The list is: " + list);
}
}

Here LinkedList is one of the sub classes of List interface and List is the sub interface of
Collection interface.

Output:
The list is: [One, Two, Three]
List Interface

 List in Java provides the facility to maintain the ordered collection.


 It contains the index-based methods to insert, update, delete and search the elements.
 It can have the duplicate elements also.
 We can also store the null elements in the list.
 The List interface is found in the [Link] package and inherits the Collection interface.
 The implementation classes of List interface are ArrayList, LinkedList, Stack and Vector.

The List interface contains various methods

void add (int index, E element)


It is used to insert the specified element at the specified position in a list.

boolean add (E e)
It is used to append the specified element at the end of a list.

void clear ()
It is used to remove all of the elements from this list.

Eget (int index)


It is used to fetch the element from the particular position of the list.
etc…
Example

import [Link].*;
public class ListExample1
{
public static void main(String args[])
{
//Creating a List
List<String> list=new ArrayList<String>();

//Adding elements in the List


[Link]("Mango");
[Link]("Apple");
[Link]("Banana");
[Link]("Grapes");

//Iterating the List element using for-each loop


for(String fruit:list)
[Link](fruit);
}
}

Output:
Mango
Apple
Banana
Grapes
Set Interface

 The set is an interface available in the [Link] package.


 The set interface extends the Collection interface.
 An unordered collection or list in which duplicates are not allowed is referred to as a
collection interface.
 The set interface use collection interface's methods to avoid the insertion of the same
elements.

The Set interface includes various methods

add (element)
This method is used to add a specific element to the set. The function adds the element only
if the specified element is not already present in the set else the function returns False if the
element is already present in the Set.

addAll (collection)
This method is used to append all of the elements from the mentioned collection to the
existing set. The elements are added randomly without following any specific order.

contains(element)
This method is used to check whether a specific element is present in the Set or not.
isEmpty()
This method is used to check whether the set is empty or not.

iterator()
This method is used to return the iterator of the set. The elements from the set are returned in
a random order.

remove(element)
This method is used to remove the given element from the set. This method returns True if
the specified element is present in the Set otherwise it returns False.
Etc..

Example:
import [Link].*;
public class SetHash
{
public static void main(String[] args)
{

Set<String>hash_Set = new HashSet<String>();

hash_Set.add("One");
hash_Set.add("Two");
hash_Set.add("Three");
hash_Set.add("Four");

hash_Set.add(“Two”); // This element is not added into the list

[Link](hash_Set);
}
}

Output:
[One, Four, Two, Three]

Note: Set interface not allowed duplicated elements


Sorted Set

 SortedSet is the alternate of Set interface that provides a total ordering on its elements.

 The elements of the SortedSet are arranged in the increasing (ascending) order.

 The SortedSet provides the additional methods that inhibit the natural ordering of the
elements.

 All the elements must be mutually comparable.

The SortedSet interface includes various methods


comparator()
Returns the comparator which is used to order the elements in the given set. Also returns null
if the given set uses the natural ordering of the element.

first()
Returns the first element from the current set.

last()
Returns the reverse order view of the mapping which present in the map.
Etc..
Example:
import [Link];
import [Link];
import [Link].*;

public class Test


{
public static void main(String[] args)
{
// Create a TreeSet and inserting elements
SortedSet<Integer> s = new TreeSet<>();

// Adding Element to SortedSet


[Link](1);
[Link](5);
[Link](2);
[Link](3);
[Link](9);

// Returning the lowest element from set


[Link]("Lowest element in set is : "+ [Link]());

}
}

Output:
Lowest element in set is : 1
Example:
import [Link];
import [Link];
import [Link].*;

public class Test


{
public static void main(String[] args)
{
// Create a TreeSet and inserting elements
SortedSet<Integer> s = new TreeSet<>();

// Adding Element to SortedSet


[Link](1);
[Link](5);
[Link](2);
[Link](3);
[Link](9);

// Print all elements from Sortedset


Iterator<Integer> i = [Link]();
while ([Link]())
[Link]([Link]());
}
}

Output:
1
2
3
5
9
ArrayList:

 Java ArrayList class uses a dynamic array for storing the elements.
 It is like an array, but there is no size limit.
 We can add or remove elements anytime.
 So, it is much more flexible than the traditional array.
 The ArrayList in Java can have the duplicate elements also. It implements the List
interface so we can use all the methods of the List interface here.
 The ArrayList maintains the insertion order internally.
 We cannot create an array list of the primitive types, such as int, float, char, etc. It is
required to use the required wrapper class in such cases.
For example:
ArrayList<int> al = ArrayList<int>(); // does not work
ArrayList<Integer> al = new ArrayList<Integer>(); // works fine

Example:

import [Link].*;
public class ArrayListExample1
{
public static void main(String args[])
{
//Creating arraylist
ArrayList<String> list=new ArrayList<String>();
[Link]("Mango"); //Adding object in arraylist
[Link]("Apple");
[Link]("Banana");
[Link]("Grapes");

//Printing the arraylist object


[Link](list);
}
}

Output:
[Mango, Apple, Banana, Grapes]
HashSet:
 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 is the best approach for search operations.

Example:
import [Link].*;
class HashSet1{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet();
[Link]("One");
[Link]("Two");
[Link]("Three");
[Link]("Four");
[Link]("Five");
[Link]("Five");
Iterator<String> i=[Link]();
while([Link]())
{
[Link]([Link]());
}
}
}

Output:
Five
One
Four
Two
Three
TreeSet:

 TreeSet class implements the Set interface that uses a tree for storage.
 It inherits Abstract Set class and implements the Navigable Set interface.
 The objects of the TreeSet class are stored in ascending order
 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 elements.
 The TreeSet can only allow those generic types that are comparable.

Example:
import [Link].*;
class TreeSet1
{
public static void main(String args[])
{
//Creating and adding elements
TreeSet<String> al=new TreeSet<String>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");

//Traversing elements
Iterator<String>itr=[Link]();
while([Link]())
{
[Link]([Link]());
}
}
}

Output:
Ajay
Ravi
Vijay
Accessing a Collection via an iterator

Iterator Interface:

 The java collection framework often we want to cycle through the elements. For
example, we might want to display each element of a collection. The java provides an
interface Iterator that is available inside the [Link] package to cycle through each
element of a collection.
 The Iterator allows us to move only forward direction.
 The Iterator does not support the replacement and addition of new elements.

We use the following steps to access a collection of elements using the Iterator.
Step - 1: Create an object of the Iterator by calling [Link]( ) method.
Step - 2: Use the method hasNext( ) to access to check does the collection has the next
element. (Use a loop).
Step - 3: Use the method next( ) to access each element from the collection. (use inside
the loop).

Methods of Iterator interface:


 Iterator iterator( ) Used to obtain an iterator to the start of the collection.
 hasNext( ) Returns true if the collection has the next element, otherwise, it
returns false.
Example:

import [Link].*;
public class TreeSetExample
{
public static void main(String[] args)
{
TreeSet set = new TreeSet();
Random num = new Random();
for(int i = 0; i < 10; i++)
[Link]([Link](100));

Iterator collection = [Link]();


[Link]("All the elements of TreeSet collection:");
while([Link]())
[Link]([Link]() + " ");
}

Output:
All the elements of TreeSet collection:
12 23 42 57 59 68 79 93 98

Common questions

Powered by AI

The 'addAll()' method in the Collection interface is used to add all elements from a specified collection into the current collection. Its main functionality is to facilitate bulk operations by allowing multiple elements to be added at once rather than one-by-one . When used with List implementations, 'addAll()' simply appends the elements to the end of the list, maintaining order and allowing duplicates. Conversely, when used with a Set implementation, 'addAll()' adds elements only if they are not already present, thereby preventing any duplicates . Additionally, in SortedSet implementations like TreeSet, elements are inserted in a sorted order .

In Java's HashSet, hashing is used to store and manage elements uniquely and efficiently. Each element's hashCode method is invoked to compute a hash code, determining the index where the element is stored in a hash table. This mechanism allows for fast access times, typically constant time complexity for add, remove, and contains operations due to direct index access based on hashed values . The impact on performance is significant as hashing allows for efficient handling of large datasets with minimal overhead. Element uniqueness is ensured as hashCode and equals methods are used in conjunction to check for duplicates before adding elements; elements are only added if their hashCode is unique or they are considered equal . This balancing of hashing and equality checking makes HashSet a powerful tool for storing non-duplicate elements efficiently .

The 'get(int index)' and 'set(int index, E element)' methods in Java's List interface provide significant advantages but also have limitations. The 'get(int index)' method allows for the retrieval of elements at specific positions, thus enabling indexed access, which is efficient for access operations due to direct indexing . The 'set(int index, E element)' method replaces the element at the specified position, facilitating updates within a List's ordered structure . However, the limitation lies in potential IndexOutOfBoundsExceptions if the specified index is out of the List's range, requiring careful index management. Both methods depend on the maintenance of correct indices, as any erroneous handling could corrupt List state or crash the program .

ArrayList in Java offers flexibility compared to traditional arrays by using a dynamic array for storing elements. Unlike traditional arrays, there is no fixed size limit with ArrayList, allowing for automatic resizing when elements are added or removed. This flexibility makes it suitable for applications where the data size may change dynamically . However, ArrayList cannot store primitive types directly; it requires these to be wrapped in their respective wrapper classes (e.g., Integer for int). Additionally, while ArrayList maintains insertion order, operations on large lists can be slower due to the automatic resizing overhead .

Java's TreeSet differs from HashSet in its handling of null elements; TreeSet does not allow null elements, while HashSet permits one null element. This difference arises because TreeSet needs to order its elements according to their natural ordering or a comparator, and null cannot be compared normally unless special handling is defined, which would violate the tree structure logic . In contrast, HashSet can include one null value since it uses hashing to store and retrieve data, which does not inherently require comparison of elements . This implies that using TreeSet to manage data requires ensuring all elements are non-null and comparable, avoiding potential NullPointerExceptions typically associated with comparisons involving null .

The SortedSet interface in Java collections enhances a regular Set by providing a total ordering on its elements. Unlike a regular Set, which does not guarantee any order, elements in a SortedSet are arranged in ascending order according to their natural ordering or a specified comparator. SortedSet offers additional methods like 'comparator()' to retrieve the comparator used, and 'first()' and 'last()' to access the first and last elements in the sorted order . This order ensures that iteration over the SortedSet yields elements in a predictable sequence .

The HashSet class and the TreeSet class differ primarily in element ordering and performance. HashSet does not maintain any order of its elements; it uses a hash table for storage which allows for efficient search operations but without any guarantee of iteration order . On the other hand, TreeSet stores its elements in a sorted order, specifically in ascending order determined either by the natural order or a specified comparator. This sorting is achieved using a tree structure, leading to generally slower access times compared to HashSet, but ensuring order during iteration .

The primary differences between the List and Set interfaces in Java's collections framework lie in their handling of element duplication and order maintenance. The List interface allows duplicate elements and maintains the order of insertion. Elements can be accessed by their index, offering an ordered collection . In contrast, the Set interface prohibits duplicate elements and does not guarantee order; elements are stored in a manner dependent on the implementation, such as HashSet which stores elements based on their hashcode .

Wrapper classes in Java collections, such as Integer for int, are significant because they allow primitive data types to be stored in collections like ArrayList, which only accept objects, not primitive types. This necessity arises because Java's collections framework is designed to work with objects, which provide useful features like the ability to be null (except for special types like Optional) and the use of methods, such as those specified in interfaces (e.g., Collection). Using wrapper classes circumvents the limitation that primitive types cannot be directly used in collections and allows for more flexible type manipulation . Additionally, certain collection methods and generic interfaces require object types for operations like equality checks and assignment .

The Iterator interface facilitates element traversal in Java collections by allowing sequential access to elements. It provides the following key methods: 'iterator()' to obtain the iterator at the start of the collection, 'hasNext()' to check if there are more elements to iterate over, and 'next()' to access the next element in the collection . Its main limitation is its forward-only traversal capability; elements cannot be replaced or added during iteration, and it does not support bi-directional movement .

You might also like