Thursday, November 16, 2023

Collections in java

 Collections

In Java, the term collections  refers to the Java Collections Framework. 

Collections which is a set of classes and interfaces in the java.util package that provide various implementations of common data structures. 

The Java Collections Framework simplifies the process of working with groups of objects, such as lists, sets, and maps.




List

List is an interface in java extends the collection interface used to ordered and index based collection of objects which may contains duplicate values.

We can store null values allso.

Types of List

1.ArrayList

2.LinkedList

3.Vector and Stack


ArrayList:-

The ArrayList class implements the List interface,means it provides all the methods specified by the List interface. 

This includes methods for adding, removing, accessing, and manipulating elements in a dynamic list.

It allows duplicates values to store and maintain a insertion order.

It is index based and random acess is allowed.

ArrayList manipulation is slow because the lot of shifting of index and values needs to be occur.It is  one  of the disadvantage of arraylist.




LinkedList:-

The LinkedList class implements the List interface,means it provides all the methods specified by the List interface. 

Unlike ArrayList, which is based on an array, LinkedList is based on a doubly-linked list data structure.

Each element in a LinkedList is represented as a node that contains a data element and references to the next and previous nodes in the sequence.
This structure allows for efficient insertion and deletion operations at both the beginning and end of the list.

It is allso allows duplicates values to store and maintains insertion order.

It has  node based datastrcture .

LinkedList manipulation is very fast because no shifting occurs.






Vector and Stack
Vector is a class in the Java Collections Framework that represents a dynamic array, capable of resizing itself to accommodate the number of elements it contains.
It implements the List interface, providing methods for adding, accessing, modifying, and removing elements.

Key Features:

Dynamic Resizing: Similar to ArrayList, Vector dynamically adjusts its size to handle the addition or removal of elements.

Synchronized: One distinctive feature is its synchronization, making it thread-safe. However, in modern Java development, synchronization is often handled differently for better performance.





Stack: LIFO Operations
Stack is a subclass of Vector that extends its capabilities to implement a last-in, first-out (LIFO) stack. 
This means that the last element added is the first one to be removed.

Key Features:

LIFO Structure: Elements are added and removed from the top of the stack.

Push and Pop Operations: It provides methods like push() for adding elements to the top and pop() for removing and returning the top element.





Set
set is an interface available in the java.util package .The set interface extends collection interface.
It is a unordered collection or list in which duplicates are not allowed.
It is widely  used in  creating mathematical set.





Types of Set
1.Hashset
2.LinkedHashSet
3.Treeset

Hashset:-
HashSet is a data structure in programming that stores a collection of unique elements where each element is unique, means it cannot contain duplicates. 
The elements in a HashSet are not stored in any particular order.

                              

Hashing Mechanism: HashSet uses a hashing mechanism to store elements. It computes a hash code for each element added to it and uses this code to determine the storage location for that element within the HashSet.
This hashing mechanism allows for fast retrieval, insertion, and deletion of elements.

Characteristics:
Addition and Retrieval: Adding an element to a HashSet checks if the element already exists by computing its hash code. If the hash code already exists in the set, it won't add a duplicate.

Performance: Offers constant-time performance for basic operations such as add, remove, contains, and size.

Unordered: Doesn’t maintain the order of elements in which they were added.
Common Usage:

Unique Element Storage: Ideal for scenarios where you need to store a collection of unique items without concern for their order.

Checking Uniqueness: Used to check whether an element is already present in the collection efficiently.


LinkedHashSet:-

A LinkedHashSet is similar to a HashSet but with an additional feature: it maintains the insertion order of elements.

Characteristics:
Uniqueness: Similar to HashSet, it contains only unique elements, meaning duplicates are not allowed.
Order Maintenance: Unlike HashSet, LinkedHashSet maintains the order in which elements are inserted. When you iterate through a LinkedHashSet, the elements are returned in the order they were added.

How it Works:
Hashing Mechanism: 
In addition to hashing, it maintains a doubly-linked list to preserve the insertion order.
Characteristics in Comparison to HashSet:
Ordered Elements: HashSet doesn’t maintain the order of elements, while LinkedHashSet does.
Performance: Offers similar performance to HashSet for basic operations with a slight overhead due to maintaining the insertion order.
Common Usage:
Preserving Order: Useful when you need a collection of unique elements and want to preserve the order in which they were added.
Iteration Order: When you need to iterate through elements in the same order they were inserted.



TreeSet
TreeSet is one of the most important implementations of the Set interface in Java that uses a Tree for storage. 
The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided

characteristics:
Sorted Order: TreeSet stores elements in a sorted order defined by either natural ordering or a custom comparator.
Unique Elements: Similar to HashSet, it contains only unique elements.

How it Works:
Red-Black Tree: Internally, TreeSet uses a Red-Black tree data structure to maintain the elements in a sorted order.
Comparator or Natural Ordering: Elements are sorted according to a Comparator provided during TreeSet instantiation or by their natural ordering if they implement the Comparable interface.
Characteristics in Comparison to HashSet and LinkedHashSet:
Ordered Elements: Unlike HashSet and LinkedHashSet, TreeSet ensures that elements are stored and traversed in a sorted order.

Performance: TreeSet provides logarithmic time cost for basic operations like add, remove, and contains, which makes it slightly slower than HashSet and LinkedHashSet for these operations.

Common Usage:
Sorted Collection: Useful when you need a set with elements sorted in a specific order.
Custom Sorting: Allows defining custom sorting behavior using a Comparator.
Unique and Sorted Elements: Combines the features of uniqueness and sorting.

Example set:-

package collection;

import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.NavigableSet;
import java.util.TreeSet;

//no insertion order is maintained ,no duplicates
public class SetExample {

public static void main(String[] args) {
HashSet<String> hs=new HashSet<String>();
hs.add("java");
hs.add("sql");
hs.add("html");
hs.add("sql");
System.out.println(hs);
hs.remove("html");
System.out.println(hs);
// hs.removeAll(hs);
// System.out.println(hs);
hs.clear();
System.out.println(hs);

TreeSet<Integer> ts=new TreeSet<Integer>();
ts.add(1);
ts.add(1);
ts.add(3);
ts.add(2);
System.out.println(ts);
        NavigableSet<Integer> descendingSet = ts.descendingSet();
        System.out.println(descendingSet);
       ts.remove(3); 
       System.out.println(ts);
       ts.removeAll(ts);
       System.out.println(ts);
    }
}







Map
In Java, the Map interface represents a collection of key-value pairs where each key is unique. 
Some commonly used implementations of the Map interface in Java include HashMap, TreeMap, LinkedHashMap, and HashTable. 



HashMap
Stores key-value pairs in a hash table.
Does not maintain any order.
Allows null keys and values (not synchronized).
Performance: Generally offers O(1) time complexity for get(), put(), remove() operations (average case).
Frequently used for general-purpose mapping.

LinkedHashMap
Similar to HashMap but is synchronized (thread-safe).
Does not allow null keys or values.
Considered legacy:ConcurrentHashMap is preferred in concurrent scenarios.
Offers slightly slower performance than HashMap due to maintaining order.
Useful when you need predictable iteration order.

HashTable
Similar to HashMap but is synchronized (thread-safe).
Does not allow null keys or values.
Considered legacy: ConcurrentHashMap is preferred in concurrent scenarios.
Slower in comparison to HashMap due to synchronization.
Used in multi-threaded environments where thread safety is required.


TreeMap
Stores keys in a sorted tree structure (usually a Red-Black Tree).
Maintains the keys in a sorted order.
Does not allow null keys but permits null values (not synchronized).
Provides O(log n) time complexity for get(), put(), remove() operations.
Useful when keys need to be sorted.

No comments:

Post a Comment