0% found this document useful (0 votes)
2 views17 pages

Day11 Collection

The document provides an overview of the Java Collection Framework, detailing its key components such as interfaces (List, Set, Map), implementations (ArrayList, LinkedList), and algorithms for data manipulation. It explains the Iterable interface and the functionalities of List and its implementations, including ArrayList and LinkedList, highlighting their memory structures and operations. The document emphasizes the benefits of using the Java Collections Framework, including efficiency, reusability, and standardization.

Uploaded by

ng4303020
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)
2 views17 pages

Day11 Collection

The document provides an overview of the Java Collection Framework, detailing its key components such as interfaces (List, Set, Map), implementations (ArrayList, LinkedList), and algorithms for data manipulation. It explains the Iterable interface and the functionalities of List and its implementations, including ArrayList and LinkedList, highlighting their memory structures and operations. The document emphasizes the benefits of using the Java Collections Framework, including efficiency, reusability, and standardization.

Uploaded by

ng4303020
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/ 17

Core Java Training

Day 11
Topics

Collection Framework –

• List,
• ArrayList,
• LinkedList
Iterable Interface
The Iterable interface in Java, found within the java.lang package, signifies that an object
can be iterated over, The primary purpose of the Iterable interface is to enable objects to
be used with the enhanced for-each loop,
The Iterable interface defines a single abstract method
public interface Iterable<T> {
Iterator<T> iterator();}

iterator(): This method returns an Iterator object, which is responsible for traversing the
elements of the Iterable object. The Iterator interface itself provides methods
like hasNext(), next(), and remove() for controlling the iteration process.
The java.util.Collection interface extends the Iterable interface. This means that all classes
implementing the Collection interface (such as ArrayList, HashSet, LinkedList, etc.) are
inherently Iterable, and thus can be used directly with the enhanced for-each loop.
Collection
A framework is a set of classes and interfaces which provide a ready-made architecture.

The Java Collection Framework is a unified architecture for storing and manipulating groups
of objects. It contains:
• Interfaces: List, Set, Map, etc.
• Classes: ArrayList, HashSet, LinkedList, HashMap, etc.
• Algorithms: Sorting, Searching, etc.

The Java Collections Framework (JCF) is a set of interfaces and classes in Java that provide a
unified architecture for representing and manipulating collections of objects. It offers a
standardized way to handle groups of data, allowing for efficient storage, retrieval, and
manipulation.
Collection
Key Components: Interfaces:

These define the abstract data types for various collections. The primary interfaces include:
• Collection: The root interface for all collection types, representing a group of
objects.
• List: An ordered collection that allows duplicate elements and provides positional
access (e.g., ArrayList, LinkedList).
• Set: A collection that stores unique elements and does not maintain insertion order
(e.g., HashSet, TreeSet).
• Queue: A collection designed for holding elements prior to processing, typically
following a First-In, First-Out (FIFO) order (e.g., PriorityQueue, ArrayDeque).
• Map: A collection that stores key-value pairs, where each key is unique
(e.g., HashMap, TreeMap). Note that Map does not extend Collection.
Collection
• Implementations:
These are concrete classes that provide the actual data structures implementing the
collection interfaces.
Examples include ArrayList, LinkedList, HashSet, TreeSet, HashMap, TreeMap, PriorityQueue,
and ArrayDeque.

• Algorithms:
The JCF also includes static methods in the Collections utility class that perform common
operations on collections, such as sorting (sort()), searching (binarySearch()), shuffling (shuffle()), and
finding minimum/maximum elements (min(), max()).
Collection Benefits:
Benefits of using the Java Collections Framework:
• Efficient data structures
• Predefined methods for storage, retrieval, and manipulation
• Dynamic memory management (no need to fix size like arrays)
• Supports:
• Iteration
• Sorting
• Searching
• Thread-safe variants (via wrappers or concurrent collections)
• Reusability: Provides ready-to-use data structures and algorithms, reducing development time.
• Standardization: Offers a consistent API for handling different types of collections.
• Performance: Implementations are optimized for various use cases.
• Interoperability: Allows different collection types to interact seamlessly.
List:
List is an interface in java.util that represents an ordered collection of elements. It allows
duplicates and provides index-based access.

Method Description

add(E e) Adds element to list

get(int index) Gets element at position

remove(int index) Removes element

set(int index, E e) Replaces element at index

size() Returns number of elements


ArryList
1. ArrayList : A resizable array, part of java.util, that implements the List interface.

import java.util.*;

public class ArrayListDemo {


public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Vineet");
names.add("Amit");
names.add("Ravi");

System.out.println(names.get(1)); //
Output: Amit
names.remove(0); // Removes "Vineet"
System.out.println(names); // [Amit, Ravi]
}
}
ArryList
Memory Structure
• ArrayList internally uses a resizable array (Object[]).
• It starts with a default capacity (usually 10).
• When it gets full, it creates a new, bigger array and copies elements.
ArrayList<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");

[ "A" ] [ "B" ] [ "C" ] [ null ] [ null ] ... (default size: 10)

• All elements are stored contiguously in memory.


• Fast index access via array[index]
• But insertion/deletion in the middle is expensive (needs shifting elements).
Major ArrayList Operations
import java.util.*; // 4. Modify element
fruits.set(1, "Pineapple"); //
public class ArrayListOperations { Replaces "Mango" with "Pineapple"
public static void main(String[] args) { System.out.println("After modifying
index 1: " + fruits);
// 1. Create an ArrayList
ArrayList<String> fruits = new // 5. Insert at specific index
ArrayList<>(); fruits.add(2, "Kiwi");
System.out.println("After inserting
// 2. Add elements at index 2: " + fruits);
fruits.add("Apple");
fruits.add("Mango"); // 6. Remove by index
fruits.add("Banana"); fruits.remove(3); // Removes
fruits.add("Orange"); "Banana"
System.out.println("After removing
System.out.println("Original List: " + index 3: " + fruits);
fruits);
// 7. Remove by value
// 3. Access element fruits.remove("Apple");
System.out.println("Element at index System.out.println("After removing
2: " + fruits.get(2)); 'Apple': " + fruits);
String Classes
// 8. Check if element exists // 12. Iterate using iterator
System.out.println("Contains System.out.println("Iterating using
'Kiwi'? " + fruits.contains("Kiwi")); Iterator:");
Iterator<String> it =
// 9. Get size fruits.iterator();
System.out.println("Size of the while (it.hasNext()) {
list: " + fruits.size()); System.out.println(it.next());
}
// 10. Sort the ArrayList
Collections.sort(fruits); // 13. Clear all elements
System.out.println("Sorted list: fruits.clear();
" + fruits); System.out.println("After clearing:
" + fruits);
// 11. Iterate using for-each
System.out.println("Iterating // 14. Check if empty
using for-each loop:"); System.out.println("Is list empty?
for (String fruit : fruits) { " + fruits.isEmpty());
System.out.println(fruit); }
} }
LinkedList
2. LinkedList : A doubly linked list implementation of the List and Deque interfaces.

import java.util.*;

Features: public class LinkedListDemo {


• Faster for insertion/deletion public static void main(String[] args) {
List<String> cities = new LinkedList<>();
• Can be used as a queue or stack cities.add("Delhi");

• Internally uses nodes (not array)


cities.add("Mumbai");
cities.add("Kolkata");

cities.add(1, "Pune"); // Insert at position


cities.remove("Delhi");

for (String city : cities) {


System.out.println(city);
}
}
}
LinkedList Memory Structure
Internal Structure: Doubly Linked List Each element (called a Node) holds:
• Data (value)
• Reference to previous node
• Reference to next node

LinkedList<String> list = new LinkedList<>();


list.add("A");
list.add("B");
list.add("C");

null ← [prev | "A" | next] [prev | "B" | next] [prev | "C" | next] → null

• Each node is stored separately in memory (not contiguous).


• Fast insertion/removal at head or tail
• Slow access by index because you must traverse node by node
LinkedList : Reverse Traversal

import java.util.LinkedList; // Print original order

import java.util.Iterator; System.out.println("Original


Order:");
public class ReverseTraversalDemo { for (String city : cities) {
public static void main(String[] System.out.println(city);
args) { }
// Use descendingIterator() for reverse traversal
// Create a LinkedList of city names
System.out.println("\nReverse
LinkedList<String> cities = new Order:");
LinkedList<>(); Iterator<String> descItr =
cities.descendingIterator();
// Add elements to the LinkedList
cities.add("Delhi"); while (descItr.hasNext()) {
cities.add("Mumbai");
cities.add("Chennai"); System.out.println(descItr.next());
cities.add("Kolkata"); }
}
}
Key Features of Java

You might also like