Collection Framework in Java

Blog
Spread the love
collection-in-java

What is a Collection in Java?

If we want to represent a group of individual Object as a single entity, then we should go for collection.

What is a Collection Framework in Java?

It contains several classes and interfaces, which can represent a group of individual objects as a single entity.

There are 9 key interfaces of collection framework –

1. Collection

2. List

3. Set

4. Sorted Set

5. Navigable Set

6. Queue

7. Map

8. Sorted Map

9. Navigable Map

Methods Present in the Collection Interface

No Method Present Inside Collection Description
1. Public boolean add (Object o) insert an object
2. Public boolean addAll(Collection c)
3. Public boolean remove (Object o) Delete an element from the collection.
4. Public boolean removeAll(Collection c) Delete an element from the collection.
removeAll(Collection c)
5. Public boolean retainAll(Collection c) To remove all objects except those, present in c.
6. Public boolean contains(Object o) To search an element.
7. Public Iterator iterator() Returns an iterator.
8. Public int size() Return the total number of elements.
9. Public Object[] toArray() Convert collection to array.

Java Collection Framework Hierarchy

framework-hierarchy

List Interface

List is the child interface of the collection. If you want to represent a group of an individual object as a single entity, where duplicates are allowed and insertion order must be preserved, then we should go for list. Many classes implement this list interface, including ArrayList, LinkedList, Vector and Stack.

Array List

Present in java.util package.

Duplicates are allowed.

Insertion order is preserved.

Null insertion is possible.

Heterogeneous objects are allowed except treeset and treemap.
Let us understand the Array list with a programmatic example:

programmatic-example

Linked List:-

Insertion order is preserved.

 Duplicates objects are allowed.

Heterogeneous objects are allowed.

It allows null insertion.

Linked List is the best choice if our frequent operation is insertion and deletion in the middle.

Singly Linked List

Doubly Linked List

Linked list with a programmatic example:

programmatic-example-1

Difference Between ArrayList and LinkedList:

Array List Linked List
In Array list, it will store the elements in consecutive memory location and hence retriever operation will become easy. In the Linked List, the element won’t be sorted in consecutive memory location and hence retriever operation will become complex.

Vector:-

Insertion order is preserved.

Duplicates are allowed.

Heterogeneous objects are allowed.

Null insertion is possible.

Every method present in the vector is synchronized, vector object is thread safe.

Stack:-

It is the child class of vector. Something specially designed it class for last in first out order (LIFO).

Queue:-

It is a child interface of collection. If you want to represent a group of individual prior to processing, then we should go for queue.

Usually queue follows FIFO order (First in First out).but based on our requirement we can implement our own priority order.

Set Interface:-

Set is the child interface of collection. If you want to represent a group of an individual object as a single entity, where duplicates are not allowed and insertion order is not preserved.

Set Interface does not contain any new method and you have to use only the collection interface method.

HashSet:-

Duplicates objects are not allowed.

Insertion orders are not preserved.

Based on hash code of object.

Null insertion is possible (only once).

HashSet is the best choice if our frequent operation is a search operation.

Heterogeneous objects are allowed.

Note:

 In HashSet duplicates are not allowed. If you are trying to insert duplicates, we want to get any compile time or runtime error, add () method simply return False.

Example 1:-

runtime-error

Example 2:-

second-example

LinkedHashSet

It is the child class of hash set.

It is exactly the same as a hashset(including constructor or method) except the following differences.

HashSet LinkedHashSet
Insertion order not preserved Insertion order preserved
Introduced in 1.2v Introduced in 1.4v

In the above, program if you replace HashSet with LinkedHashSet then..

LinkedHashSet

Sorted Set:-

SortedSet is the child interface of set. If you want to represent a group of individual object according to some sorting order without duplicates, then we should go for SortedSet.

Method in SortedSet Interface.

Method Description
Object first(); Return first element of the sorted set
Object last(); Returns last element of the sorted set
SortedSet headset(Object obj) Return SortedSet whose elements are less than obj
SortedSet tailset(Object obj) Returns SortedSet whose elements are >= obj

TreeSet:-

Duplicates objects are not allowed.

Insertion order not preserved.

Null insertion is possible (only once).

heterogeneous objects are not allowed, otherwise we will get a runtime exception.

All objects should be inserted based on some sorting order.

example-1

Note:

Null Acceptance-

For non-empty tree Set if you are trying to insert null then you will get Null Pointer Exception.

For the empty tree Set, add the first element null is allowed but after inserting that null. If you are trying to insert any other, then we will get Runtime Exception.

Until 1.6v null is allowed, add the first element to the empty tree Set, but 1.7v onwards null is not allowed. Even add the first element, i.e., null.

Map Interface

map is not child interface of collection. If you want to represent a group of object as key-value pairs, then we should go for map interface.

Both keys and value are object only.

Duplicates keys are not allowed but value can be duplicated.

HashMap:-

HashMap is like HashTable, but it is unsynchronized.

Insertion order is not preserved, and it is based on hash code of keys.

Duplicate keys are not allowed, but values can be duplicated.

Null is allowed for key (only once), and null is allowed for value (many times).

HashMap is the best choice if our frequent operation is a search operation.

Heterogeneous objects are allowed for both key and value.

Constructors

HashMap h = new HashMap ();

Creates an empty HashMap object with default initial capacity 16, and default fill ratio 0.75 .

HashMap h = new HashMap (int initialcapacity);

Creates an empty HashMap object with a specified initial capacity and default fill ratio 0.75.

Example :

example-2

LinkedHashMap:-

It is the child class of HashMap.it is exactly the same as the Hashmap.

A Linked HashMap contains values based on the key.

It contains only unique elements.

It may have one null key and multiple null values.

It is non-synchronized.

Insertion  is preserved.

Example:-

preserved-example

IdentityHashMap

It is exactly the same as HashMap (including method or constructor) except the following differences:

In the case of HashMap JVM will use. equals () method to identify duplicate keys.

But in the case of identity hash map JVM will use == (double equal operator) to identify duplicate key

It is not synchronized and must be synchronized externally.

WeakHashMap

It is an implementation of the Map interface.

In case of weak hashmap , if an object does not contain any references, it is eligible for garbage collection.

Garbage collector dominates over weak hashmap.

TreeMap:-

Insertion order is not preserved, and it is based on some sorting order keys.

Duplicates keys are not allowed but value can be duplicated.

It is non synchronized.

TreeMap maintains ascending order.

TreeMap contains only unique elements.

Example:

TreeMap-example

HashTable:-

It is like HashMap, but is synchronized.

Insertion order is not preserved, and it is based on hash code of keys.

Heterogeneous objects are allowed for both key and value.

Duplicates keys are not allowed but value can be duplicated,

Null is not allowed for both key and value.

Every method present in HashTable is synchronized and hence Hash table object is thread safe.

The initial default capacity of the HashTable class is 11 whereas load factor is 0.75.

HashTable is the best choice if our frequent operation is a search operation.

Hierarchy of Hashtable

Hierarchy-example

Constructors:-

HashTable h = new HashTable();

Creates an empty hashtable object with default initial capacity 11 and default fill ratio 0.75.

HashTable h = new HashTable(int initialcapacity);

HashTable h = new Hashtable(int initialcapacity,float fillratio);

Example:

initialcapacity

This blog illustrate the collection framework. Which is useful for java developer while writing efficient code.

bluethinkinc_blog

bluethinkinc_blog

2023-01-02

0

Leave a Reply

Your email address will not be published. Required fields are marked *

Find More Blogs

How to Add a Custom Tab to the Customer Order Detail Page in Magento 2

Spread the love Adding a custom tab to the Order Detail

Exception Handling in Java

Spread the love Introduction – Exception:An unwanted

How to add custom less file in Magento2

Spread the love Source files *.css included into layout

Spring Boot Microservices

Spread the love Microservices architecture has become

Implementation of WireMock for better testing

Spread the love WireMock is a flexible and powerful tool

Magento 2: How to selected default option in configurable options?

Spread the love Configurable products in Magento 2 allow

How To Implement Simple JWT Authentication in Django Rest Framework

Spread the love We’ll learn how to use simple JWT

Optimizing Search: Integrating Elasticsearch in Django Applications

Spread the love What is Elasticsearch? Elasticsearch is a

How to create Customer Segments

Spread the love In Magento 2, “customer

Proxy Design Pattern and Requisition List in Magento 2

Spread the love Requisition List in Magento 2 Requisition

bluethinkinc Blogs