0% found this document useful (0 votes)
8 views

Java Collection Framework

The Java Collections Framework (JCF) is a set of classes and interfaces in the java.util package that facilitates efficient data storage and manipulation. It includes core components like interfaces (Collection, List, Set, Queue, Map), implementations (ArrayList, HashSet, HashMap, etc.), and utilities for operations such as sorting and searching. Key features include ordered collections with duplicates in Lists, unique elements in Sets, and key-value pairs in Maps, each with specific implementations and use cases.

Uploaded by

jaykumarguptajti
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)
8 views

Java Collection Framework

The Java Collections Framework (JCF) is a set of classes and interfaces in the java.util package that facilitates efficient data storage and manipulation. It includes core components like interfaces (Collection, List, Set, Queue, Map), implementations (ArrayList, HashSet, HashMap, etc.), and utilities for operations such as sorting and searching. Key features include ordered collections with duplicates in Lists, unique elements in Sets, and key-value pairs in Maps, each with specific implementations and use cases.

Uploaded by

jaykumarguptajti
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
You are on page 1/ 23

Java Collection Framework (JCF)

1.​ java.lang.Iterable
●​ java.util.Collection

○​ java.util.List
■​ ArrayList
■​ LinkedList
■​ Vector
●​ Stack

○​ java.util.Set
■​ HashSet
■​ LinkedHashSet
■​ TreeSet

○​ java.util.Queue
■​ PriorityQueue
■​ java.util.Deque
●​ ArrayDeque
●​ LinkedList

●​ java.util.Map (separate hierarchy)


○​ HashMap
○​ LinkedHashMap
○​ TreeMap
The Java Collections Framework (JCF) provides a set of classes and interfaces to store and
manipulate data efficiently. It is part of the java.util package and supports operations like searching,
sorting, insertion, deletion, and more.

Key Components of Java Collections:

1.​ Interfaces: Define the core structure of a collection. Examples:


●​ Collection: The root interface.
●​ List: Ordered collection (e.g., ArrayList, LinkedList).
●​ Set: Unique elements (e.g., HashSet, TreeSet).
●​ Queue: FIFO (e.g., PriorityQueue, Deque).
●​ Map: Key-value pairs (e.g., HashMap, TreeMap).
2.​ Implementations: Concrete classes implementing these interfaces.
●​ List: ArrayList, LinkedList, Vector.
●​ Set: HashSet, LinkedHashSet, TreeSet.
●​ Queue: PriorityQueue, Deque.
●​ Map: HashMap, TreeMap, LinkedHashMap.
3.​ Utilities:
●​ Collections: Utility class for sorting, searching, and synchronisation.
●​ Arrays: Converts arrays to collections and vice versa.

Step 1: Lists in Java Collections

Definition of List Interface

The List interface in Java is part of the Collections Framework and represents an ordered collection
of elements. It allows duplicate values and provides control over where each element is inserted or
accessed using an index.

Why Use a List?

1.​ Order: Maintains the order of insertion.


2.​ Index-based Access: You can access, add, or remove elements at specific positions using
indices.
3.​ Duplicates: Allows duplicate elements, making it ideal for scenarios where repeating data is
needed.

Core Implementations of List (Classes)

1.​ ArrayList:​

○​ Backed by a dynamic array.


○​ Fast random access (via indices). O(1)
○​ Slow insertion/deletion for large lists (as elements are shifted). O(n)
2.​ LinkedList:​

○​ Backed by a doubly linked list.


○​ Efficient insertion/deletion at the beginning or middle. O(1)
○​ Slower random access (traversal required). O(n)
3.​ Vector:​

○​ Similar to ArrayList but synchronised for thread safety.


○​ Rarely used in modern applications.
○​ Stack is also a class that extends vector. It is LIFO push, pop, peek etc.

Feature ArrayList LinkedList

Data Structure Dynamic Array Doubly Linked List

Access Time Fast (O(1)) for random access Slow (O(n)) due to traversal

Insertion/Deletion Slow (O(n)) for large lists Fast (O(1)) at head/tail

Memory Usage Less (compact) More (due to pointers)

Best Use Case Frequent reads, fewer updates Frequent insertions/deletions

Practical Implementations

ArrayList Example

import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
List<String> list = new ArrayList<>();

// Adding elements
list.add("Apple");
list.add("Banana");
list.add("Cherry");

// Accessing elements
System.out.println("Element at index 1: " + list.get(1));

// Iterating

System.out.println("Iterating over the list:");


for (String fruit : list) {
System.out.println(fruit);
}

Iterator<String> it = list.iterator();
while(it.hasNext()) {
​ System.out.println(it.next());
}
// Removing an element
list.remove("Banana");
list.remove(index no);
System.out.println("After removal: " + list); // list as an Object (to String chlegi)
}
}

LinkedList Example
import java.util.LinkedList;

public class LinkedListExample {


public static void main(String[] args) {
List<String> list = new LinkedList<>();
LinkedList<String> list = new LinkedList<>();

// Adding elements
list.add("Lion");
list.add("Tiger");
list.add("Elephant");

// Adding at specific position


list.addFirst("Panda"); // of LinkedList
list.addLast("Giraffe");
list.add(index, element);

// Accessing elements
System.out.println("First Element: " + list.getFirst());
System.out.println("Last Element: " + list.getLast());

// Removing elements
list.removeFirst();
list.removeLast();
System.out.println("After removal: " + list);
}
}

Vector Example
import java.util.Vector;

public class VectorExample {


public static void main(String[] args) {
Vector<Integer> vector = new Vector<>();

// Adding elements
vector.add(10);
vector.add(20);
vector.add(30);

// Accessing elements
System.out.println("Element at index 2: " + vector.get(2));

// Removing an element
vector.remove((Integer) 20);
System.out.println("After removal: " + vector);
}
}
Stack Example

import java.util.*;
public class Main {
public static void main(String[] args) {
Stack<Integer> st = new Stack<>();

// Adding elements
st.push(10);
st.push(20);
st.push(30);
st.push(40);

System.out.println(st); // [10,20,30,40]

// Accessing top elements


System.out.println("Element: " + st.peek());

// remove from the top


int top = st.pop();
System.out.println(top);

// size of the stack


System.out.println("Size of stack : "+ st.size());
}
}

Iterating Through Lists

For Loop:​

for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}

Enhanced For Loop:​



for (String item : list) {
System.out.println(item);
}

Iterator:​

Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
Step 2: Sets in Java Collections

Definition of Set Interface

The Set interface in Java is part of the Collections Framework and represents a collection of unique
elements. It does not allow duplicate values, making it ideal for scenarios where uniqueness is
required.

Why Use a Set?

1.​ No Duplicates: Ensures that all stored elements are distinct.


2.​ Efficient Membership Checking: Quickly checks if an element exists.
3.​ Various Implementations: Supports unordered, insertion-ordered, and sorted data.

Core Implementations of Set

1.​ HashSet:​

○​ Backed by a HashMap.
○​ Unordered collection.
○​ Provides constant-time performance for basic operations (add, remove, contains).
2.​ LinkedHashSet:​

○​ Subclass of HashSet.
○​ Maintains insertion order.
○​ Slightly slower than HashSet due to maintaining a linked list.
3.​ TreeSet:​

○​ Implements the SortedSet interface.


○​ Backed by a Red-Black Tree.
○​ Keeps elements in sorted (ascending) order.
○​ Provides logarithmic time complexity for operations.

Comparison: HashSet vs LinkedHashSet vs TreeSet


Feature HashSet LinkedHashSet TreeSet

Ordering Unordered Insertion order Sorted (ascending)

Duplicates Not allowed Not allowed Not allowed

Performance Best for large data Slightly slower Slowest

Time Complexity O(1) (average) O(1) (average) O(log n)

Null Handling Allows one null Allows one null Does not allow null

Best Use Case Fast membership check Ordered unique data Sorted unique data
Practical Implementations

HashSet Example
import java.util.HashSet;

public class HashSetExample {


public static void main(String[] args) {
HashSet<String> set = new HashSet<>();

// Adding elements
set.add("Apple");
set.add("Banana");
set.add("Cherry");

// Attempting to add duplicate


set.add("Apple");

// Display elements
System.out.println("HashSet: " + set);

// Check for an element


System.out.println("Contains 'Banana'? " + set.contains("Banana"));

// Removing an element
set.remove("Banana");
System.out.println("After removal: " + set);
}
}

LinkedHashSet Example
import java.util.LinkedHashSet;

public class LinkedHashSetExample {


public static void main(String[] args) {
LinkedHashSet<String> set = new LinkedHashSet<>();

// Adding elements
set.add("Lion");
set.add("Tiger");
set.add("Elephant");

// Display elements (insertion order)


System.out.println("LinkedHashSet: " + set);

// Removing an element
set.remove("Tiger");
System.out.println("After removal: " + set);
}
}
TreeSet Example
import java.util.TreeSet;

public class TreeSetExample {


public static void main(String[] args) {
TreeSet<Integer> set = new TreeSet<>();

// Adding elements
set.add(40);
set.add(10);
set.add(30);
set.add(20);

// Display elements (sorted order)


System.out.println("TreeSet: " + set); 10,20,30,40

// Retrieve first and last elements


System.out.println("First: " + set.first());
System.out.println("Last: " + set.last());

// Removing an element
set.remove(20);
System.out.println("After removal: " + set);
}
}

Iterating Through Sets


Enhanced For Loop:​

for (String item : set) {
System.out.println(item);
}

Iterator:​

Iterator<String> iterator = set.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}

No entrySet() for Set


Step 4: Maps in Java Collections

Definition of Map Interface

The Map interface in Java is part of the Collections Framework and is used to store key-value pairs.
Each key in a Map must be unique, while the values can be duplicate. A Map is perfect when you need to
associate data (values) with unique identifiers (keys).

Why Use a Map?

1.​ Key-Value Mapping: Useful for scenarios where you want to look up values using unique keys
(e.g., student roll numbers and marks).
2.​ Efficient Retrieval: Provides fast access to values based on their keys.
3.​ Prevents Duplicate Keys: Guarantees that each key is unique.

Core Implementations of Map

1.​ HashMap:​

○​ Backed by a hash table.


○​ Does not maintain any order.
○​ Allows one null key and multiple null values.
○​ Provides constant-time performance for basic operations (put, get, remove) on
average.
2.​ LinkedHashMap:​

○​ Extends HashMap and maintains insertion order.


○​ Slightly slower than HashMap due to the additional overhead of maintaining the order.
3.​ TreeMap:​

○​ Implements the NavigableMap interface and uses a Red-Black Tree.


○​ Maintains sorted (ascending) order of keys.
○​ Does not allow null keys but allows multiple null values.
4.​ Hashtable:​

○​ Synchronized version of HashMap for thread-safe operations.


○​ Does not allow null keys or null values.
Comparison: HashMap vs LinkedHashMap vs TreeMap vs Hashtable
Feature HashMap LinkedHashMap TreeMap Hashtable

Ordering Unordered Insertion order Sorted by keys Unordered

Duplicates Keys not allowed Keys not allowed Keys not allowed Keys not allowed

Null One null key One null key No null keys No null keys/values
Handling

Thread Not thread-safe Not thread-safe Not thread-safe Thread-safe


Safety

Performance Fastest Slightly slower Slower (log n) Slowest

Best Use General-purpose Ordered key-value Sorted key-value Legacy/thread-safe


Case

Practical Implementations

HashMap Example
import java.util.HashMap;

public class HashMapExample {


public static void main(String[] args) {
// Creating a HashMap
HashMap<Integer, String> map = new HashMap<>();

// Adding key-value pairs


map.put(1, "John");
map.put(2, "Alice");
map.put(3, "Bob");
map.put(3, “Ayush”); // override

// Accessing a value
System.out.println("Value for key 2: " + map.get(2));

// Removing a key-value pair


map.remove(3);
System.out.println("After removal: " + map);

// Iterating through the map


System.out.println("Iterating over the map:");
for (Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
}
}
LinkedHashMap Example
import java.util.LinkedHashMap;

public class LinkedHashMapExample {


public static void main(String[] args) {
LinkedHashMap<Integer, String> map = new LinkedHashMap<>();

// Adding key-value pairs


map.put(1, "Red");
map.put(2, "Green");
map.put(3, "Blue");

// Accessing a value
System.out.println("Value for key 1: " + map.get(1));

// Display elements (maintains insertion order)


System.out.println("LinkedHashMap: " + map);
}
}

TreeMap Example
import java.util.TreeMap;

public class TreeMapExample {


public static void main(String[] args) {
TreeMap<Integer, String> map = new TreeMap<>();

// Adding key-value pairs


map.put(3, "Three");
map.put(1, "One");
map.put(2, "Two");

// Display elements (sorted by key)


System.out.println("TreeMap: " + map);

// Accessing first and last entries


System.out.println("First Entry: " + map.firstEntry());
System.out.println("Last Entry: " + map.lastEntry());
}
}
Hashtable Example
import java.util.Hashtable;

public class HashtableExample {


public static void main(String[] args) {
Hashtable<String, Integer> table = new Hashtable<>();

// Adding key-value pairs


table.put("A", 100);
table.put("B", 200);
table.put("C", 300);

// Accessing a value
System.out.println("Value for key 'B': " + table.get("B"));

// Removing a key-value pair


table.remove("C");
System.out.println("After removal: " + table);
}
}

Common Operations on Maps

1.​ Add Elements:


○​ put(key, value)
2.​ Remove Elements:
○​ remove(key)
3.​ Access Values:
○​ get(key)
4.​ Check Key/Value Existence:
○​ containsKey(key)
○​ containsValue(value)
5.​ Iterate Through Map:
○​ Using keySet(), entrySet(), or values().

Iterating Through Maps


Using entrySet():​

for (Map.Entry<K, V> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
Using keySet():​

for (K key : map.keySet()) {
System.out.println("Key: " + key + ", Value: " + map.get(key));}
Using values():​

for (V value : map.values()) {
System.out.println("Value: " + value);
}
import java.util.*;

class Student
{
private int rollNumber;
private String name;

Student()
{

}
Student(int rollNumber, String name)
{
this.rollNumber = rollNumber;
this.name = name;
}

public int getRollNumber()


{
return this.rollNumber;
}
public String getName()
{
return this.name;
}
}

Student Object in a Map



public class Main
{
public static void main(String[] args)
{
// Creating a HashMap
Map<Integer, Student> map = new HashMap<>();

Student s1 = new Student(41, "Ayush");


Student s2 = new Student(07, "Khushi");
Student s3 = new Student(13, "Adarsh");
Student s4 = new Student(13, "Rana");

map.put(s1.getRollNumber(), s1);
map.put(07, s2);
map.put(13, s3);
map.put(s4.getRollNumber(), s4); // roll number wise key hai no problem (override)

System.out.println("Size: " + map.size());


// get with key
System.out.println("get at 41: "+ map.get(41).getName());

// iteration
for(Map.Entry<Integer, Student> entry : map.entrySet())
{
Integer key = entry.getKey();
Student s = entry.getValue();
System.out.println("Key: "+ key + " Roll Number: " + s.getRollNumber() + " Name: "+ s.getName());
}

}
}

Step 4: Queues in Java Collections

Definition of Queue

A Queue in Java is a linear data structure that operates in a FIFO (First In, First Out) manner. This
means elements are inserted at the end (tail) and removed from the front (head). Queues are
particularly useful for scenarios like scheduling tasks, message buffering, or breadth-first search in
graphs.

The Queue interface is part of the Java Collections Framework and extends the Collection interface.

Why Use a Queue?

1.​ Order Management: Queues ensure the order of elements is preserved (FIFO).
2.​ Task Scheduling: Commonly used in task scheduling or handling requests in the order they
arrive.
3.​ Separation of Concerns: Queues abstract the details of data processing order.

Core Implementations of Queue ( all allowed duplicates)


Queue Implementation Description Ordering

LinkedList Implements both Queue and Deque Insertion order


interfaces. A general-purpose queue
implementation.

PriorityQueue An implementation where elements are Priority-based order


ordered based on their natural ordering or a
comparator.

ArrayDeque A resizable array-based implementation of Insertion order


Deque and Queue. More efficient than
LinkedList.
Basic Queue Methods
Method Description

add(element) Inserts an element into the queue. Throws an exception if the


queue is full.

offer(element Inserts an element into the queue. Returns false if the queue is
) full.

remove() Removes and returns the head of the queue. Throws an


exception if the queue is empty.

poll() Removes and returns the head of the queue, or null if the
queue is empty.

element() Retrieves the head of the queue without removing it. Throws an
exception if the queue is empty.

peek() Retrieves the head of the queue without removing it, or null if
the queue is empty.

Comparison: LinkedList vs PriorityQueue vs ArrayDeque


Feature LinkedList PriorityQueue ArrayDeque

Ordering FIFO Natural or FIFO


Comparator-based

Null Allowed Not allowed Not allowed


Elements

Performanc Moderate Moderate Fast


e

Use Case General-purpose Priority-based tasks High-performance


queue queue

Time Complexity of Queue Operations


Operation LinkedList PriorityQueue ArrayDeque

Add O(1) O(log n) O(1)

Remove O(1) O(log n) O(1)

Peek O(1) O(1) O(1)


Practical Implementations

1. Queue Using LinkedList


import java.util.LinkedList;
import java.util.Queue;

public class QueueExample {


public static void main(String[] args) {
Queue<Integer> queue = new LinkedList<>();

// Adding elements
queue.add(10);
queue.add(20);
queue.add(30);

// Display the queue


System.out.println("Queue: " + queue);

// Access the head of the queue


System.out.println("Head: " + queue.peek());

// Remove elements
System.out.println("Removed: " + queue.poll());
System.out.println("Queue after removal: " + queue);
}
}

2. PriorityQueue Example
import java.util.PriorityQueue;

public class PriorityQueueExample {


public static void main(String[] args) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder()); // largest first

PriorityQueue<Integer> pq = new PriorityQueue<>( new Comparator<Integer>(){
public int compare(Integer a, Integer b)
{
return b - a;
}
});

PriorityQueue<Integer> pq = new PriorityQueue<>( (a,b) -> b - a );

// Adding elements (natural order)


pq.add(30);
pq.add(10);
pq.add(20);
// Display the priority queue
System.out.println("PriorityQueue: " + pq); // 10, 30, 20 (smallest at the top)

// Access and remove elements (priority order)


while (!pq.isEmpty()) {
System.out.println("Removed: " + pq.poll());
} }}

3. ArrayDeque Example
import java.util.*;

public class Main {


public static void main(String[] args) {
ArrayDeque<String> queue = new ArrayDeque<>();

// Adding elements
queue.offer("A");
queue.offer("B");
queue.offer("C");
queue.offerFirst("a");
queue.offerLast("Z");

// Display the queue


System.out.println("Queue: " + queue);

// Access the head


System.out.println("Head: " + queue.peek());
System.out.println("Head: " + queue.peekFirst());
System.out.println("Head: " + queue.peekLast());

// Remove elements
System.out.println("Removed: " + queue.poll());
System.out.println("Removed: " + queue.pollLast());
System.out.println("Queue after removal: " + queue);
}
}
Step 5: Utilities in Java Collections
The java.util.Collections class provides utility methods to operate on collections, such as sorting,
searching, reversing, and thread-safety wrappers. These utilities are static methods that work on List,
Set, and Map types, offering common operations efficiently and conveniently.

Key Categories of Utility Methods

1.​ Sorting and Searching:


●​ sort()
i.​ Collections.sort(list);
ii.​ Collections.sort(list, Comparator.reverseOrder());
●​ binarySearch()
i.​ int index = Collections.binarySearch(numbers, 5);
2.​ Min/Max Operations:
●​ min(), max()
i.​ int min = Collections.min(numbers);
ii.​ int max = Collections.max(numbers);
3.​ Shuffling and Rotating:
●​ shuffle(), rotate()
i.​ Collections.shuffle(items);
4.​ Frequency and Disjoint
●​ frequency() counts the occurrences of an element in a collection.
●​ disjoint() checks if two collections have no elements in common.

List<String> list = Arrays.asList("A", "B", "A", "C");

int frequency = Collections.frequency(list, "A");

System.out.println("Frequency of 'A': " + frequency);

List<String> list2 = Arrays.asList("X", "Y");

boolean areDisjoint = Collections.disjoint(list, list2);

System.out.println("Are the lists disjoint? " + areDisjoint);

5.​ Empty Collections:


●​ emptyList(), emptySet(), emptyMap()
​ C++ STL
​ The Standard Template Library (STL) in C++ is a powerful library that provides a set of generic classes and

functions to manage collections of data. It includes components for data structures and algorithms, designed to

work together seamlessly.

​ Major Components of STL:


●​ Containers: These are used to store data. They define how the data is stored and accessed.
●​ Sequence Containers: vector, list, deque, array
●​ Associative Containers: set, map, multiset, multimap
●​ Unordered Containers: unordered_set, unordered_map, unordered_multiset,
unordered_multimap
●​ Iterators: These are used to traverse through the containers, similar to pointers. They provide a uniform
way to access container elements.
●​ Types: begin(), end(), next(), prev(), etc.
●​ Algorithms: STL provides a collection of algorithms that can be used on containers. These algorithms
are generic and can work on any container type.
●​ Examples: sort(), find(), reverse(), copy(), accumulate()
●​ Functors (or Function Objects): These are objects that can be called as if they are functions. They are
used with algorithms to provide flexibility.
●​ Example: std::greater, std::less
●​

​ 1. Containers:
●​ Containers are data structures that store and organize data. STL provides several types of containers,
categorized as:​
Sequence Containers:
●​ vector: Dynamic array; supports fast random access and amortized constant-time push_back.
●​ list: Doubly linked list; good for insertions and deletions anywhere in the container but slower
random access.
●​ deque: Double-ended queue; supports efficient push and pop at both ends.
●​ array: Fixed-size array; offers faster access with a constant size at compile-time.
●​ Associative Containers (Ordered based on key):
●​ set: Stores unique elements in a sorted order.
●​ map: Stores key-value pairs with unique keys in sorted order.
●​ multiset: Allows duplicate elements in a sorted order.
●​ multimap: Allows duplicate key-value pairs in sorted order.
●​ Unordered Containers (Based on hash tables):
●​ unordered_set, unordered_map, unordered_multiset, unordered_multimap: Provide faster
access compared to associative containers but don't maintain element order.
​ 2. Iterators:
●​ Iterators are used to traverse containers. They abstract away the internal structure of containers.
●​ Types:
●​ begin(): Points to the first element.
●​ end(): Points one past the last element.
●​ next(), prev(): Move iterators forward or backward.
●​ reverse_iterator: Iterates in reverse order.
●​ Iterators provide a uniform interface for working with all container types, enabling algorithms to operate
on any container.

​ 3. Algorithms:
●​ STL algorithms are a set of functions that can be used on containers via iterators. These algorithms
provide commonly needed functionality like sorting, searching, and modifying data.
●​ Examples:
●​ Sorting: std::sort(), std::stable_sort()
●​ Searching: std::find(), std::binary_search()
●​ Modifying: std::reverse(), std::fill()
●​ Others: std::accumulate(), std::count(), std::copy()
●​ They operate on iterators, making them flexible for different container types.
​ 4. Functors (Function Objects):
●​ Functors are objects that can be used as functions. They are used with STL algorithms for custom
behaviors like comparison or transformation.
●​ Example:
●​ std::sort(v.begin(), v.end(), std::greater<int>()) sorts a vector v in descending
order using a functor std::greater.
●​ Functors allow passing customized behavior into algorithms instead of using traditional function
pointers.
​ Advantages of STL:
●​ Reusability: Containers, iterators, and algorithms can be used together with minimal effort.
●​ Efficiency: STL algorithms are often optimized for performance, leveraging the underlying data
structures efficiently.
●​ Flexibility: It supports different kinds of containers and algorithms to meet various requirements.
●​ Type Safety: STL uses templates to ensure type safety at compile-time.


​ ChatGPT said:
​ Here are the basic methods for some common STL containers and their typical operations:

​ 1. vector (Dynamic Array):


●​ push_back(): Adds an element at the end.
●​ pop_back(): Removes the last element.
●​ size(): Returns the number of elements.
●​ empty(): Checks if the vector is empty.
●​ at(): Accesses an element with bounds checking.
●​ operator[]: Accesses an element without bounds checking.
●​ begin() / end(): Returns an iterator to the first/last element.
●​ insert(): Inserts elements at a specific position.
●​ erase(): Removes elements from a specific position.

​ 2. list (Doubly Linked List):


●​ push_back(): Adds an element at the end.
●​ push_front(): Adds an element at the beginning.
●​ pop_back(): Removes the last element.
●​ pop_front(): Removes the first element.
●​ size(): Returns the number of elements.
●​ empty(): Checks if the list is empty.
●​ begin() / end(): Returns iterators to the first/last element.
●​ insert(): Inserts elements at a specific position.
●​ erase(): Removes elements from a specific position.


​ 3. deque (Double-Ended Queue):
●​ push_back(): Adds an element at the end.
●​ push_front(): Adds an element at the front.
●​ pop_back(): Removes the last element.
●​ pop_front(): Removes the first element.
●​ size(): Returns the number of elements.
●​ empty(): Checks if the deque is empty.
●​ at(): Accesses an element with bounds checking.
●​ operator[]: Accesses an element without bounds checking.
●​ begin() / end(): Returns iterators to the first/last element.

​ 4. set (Ordered Set):


●​ insert(): Inserts an element, if not already present.
●​ erase(): Removes a specific element.
●​ find(): Finds an element, returns an iterator.
●​ size(): Returns the number of elements.
●​ empty(): Checks if the set is empty.
●​ begin() / end(): Returns iterators to the first/last element.

​ 5. map (Ordered Key-Value Pair):


●​ insert(): Adds a key-value pair.
●​ erase(): Removes a key-value pair by key.
●​ find(): Finds a key, returns an iterator.
●​ at(): Accesses the value associated with a key.
●​ operator[]: Accesses the value associated with a key (or inserts if not found).
●​ size(): Returns the number of key-value pairs.
●​ empty(): Checks if the map is empty.
●​ begin() / end(): Returns iterators to the first/last key-value pair.

​ 6. unordered_set (Unordered Set, Hash Table):


●​ insert(): Inserts an element.
●​ erase(): Removes an element.
●​ find(): Finds an element, returns an iterator.
●​ size(): Returns the number of elements.
●​ empty(): Checks if the set is empty.
●​ begin() / end(): Returns iterators to the first/last element.

​ 7. unordered_map (Unordered Key-Value Pair, Hash Table):


●​ insert(): Adds a key-value pair.
●​ erase(): Removes a key-value pair by key.
●​ find(): Finds a key, returns an iterator.
●​ at(): Accesses the value associated with a key.
●​ operator[]: Accesses the value associated with a key (or inserts if not found).
●​ size(): Returns the number of key-value pairs.
●​ empty(): Checks if the map is empty.
●​ begin() / end(): Returns iterators to the first/last key-value pair.

​ 8. stack (LIFO Stack):


●​ push(): Adds an element to the stack.
●​ pop(): Removes the top element.
●​ top(): Returns the top element.
●​ empty(): Checks if the stack is empty.
●​ size(): Returns the number of elements.
​ 9. queue (FIFO Queue):
●​ push(): Adds an element to the back of the queue.
●​ pop(): Removes the front element.
●​ front(): Returns the front element.
●​ back(): Returns the back element.
●​ empty(): Checks if the queue is empty.
●​ size(): Returns the number of elements.

​ 10. priority_queue (Max Heap by default):


●​ push(): Adds an element.
●​ pop(): Removes the top element (highest priority).
●​ top(): Returns the top element (highest priority).
●​ empty(): Checks if the priority queue is empty.
●​ size(): Returns the number of elements.

C vs C++

C C++
Procedural OOPL
Mid level High level
Top-down bottom-up
32 keywords 96 keywords
No overloading overloading
Namespace concept No Namespace concept
Malloc , calloc New and delete
Extension .c .cpp or c++
Denies Ritchie 1972 Bjarne Stroustrup 1979

C++ vs java
1.​Platform dependency
2.​Primitive Pointer
3.​Multiple Inheritance
4.​Virtual keyword
5.​No Distructor
6.​Garbage Collection
7.​Java James Gosling 1995

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy