SlideShare a Scribd company logo
Collection Class Implementations
Learning Outcome
• Understand the working and methods in classes
– ArrayList
– LinkedList
– Queue
– Set
– Trees
• Interfaces
– Iterator
– ListIterator
Collection class- ArrayList
• ArrayList supports dynamic arrays that can grow as needed
• ArrayList is a variable-length array of object references.
• An ArrayList can dynamically increase or decrease insize.
• Array lists are created with an initial size
• When this size is exceeded, the collection is automatically
enlarged. When objects are removed, the array can be
shrunk.
• public class ArrayList<E> extends AbstractList<E> implements
List<E>, RandomAccess, Cloneable, Serializable
Collection implementation classes - Arraylist, linkedlist, Stack
ArrayList- methods
• ArrayList( )
• ArrayList(Collection<? extends E> c)
• ArrayList(int capacity)
• void ensureCapacity(int cap) – to increase
capacity manually to avoid reallocations
• void trimToSize( ) – to reduce size manually
• object[ ] toArray( )
• <T> T[ ] toArray(T array[ ])
Original List: [India, China, US, Germany,
Bhutan]
After add: [India, China, US, SriLanka,
Germany, Bhutan]
After remove: [India, US, SriLanka,
Bhutan]
alist.size()  0
alist.size()  5
ArrayList
After Sort: [Bhutan, India, SriLanka, US]
After reverse: [US, SriLanka, India,
Bhutan]
Using get(): India
After subList: [SriLanka, India]
After set: [Nepal, India]
After Combine: [US, SriLanka, India,
Bhutan, Nepal, India]
For loop – iterated through List
for(String v : alist)
{
System.out.print(v + “*** ");
}
US *** SriLanka*** India***Bhutan***Nepal***India
Storing user defined class in ArrayList
import java.util.*;
class Book
{
private String title;
private int price;
Book(String title, int price)
{
this.title=title;
this.price=price;
}
@Override
public String toString() {
return "Title is: "+this.title+"n" +" Price is: "+this.price;
}
}
Storing user defined class in ArrayList
class BookList {
public static void main(String args[]) {
ArrayList<Book> al= new ArrayList<Book>();
al.add(new Book("Java Fundamentals", 340));
al.add(new Book("Data Structure", 140));
al.add(new Book("Python Programming", 320));
for (Book tmp: al)
System.out.println(tmp);
}
}
Output:
Title is: Java Fundamentals
Price is: 340
Title is: Data Structure
Price is: 140
Title is: Python Programming
Price is: 320
Linked List class
• public class LinkedList<E> extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, Serializable
• LinkedList( )
• LinkedList(Collection<? extends E> c)
• To add elements to the start of list - addFirst( ) or offerFirst( ).
• To add elements to the end of list - addLast( ) or offerLast( ).
• To obtain the first element - getFirst( ) or peekFirst( ).
• To obtain the last element - getLast( ) or peekLast( ).
• To remove the first element - removeFirst( ) or pollFirst( ).
• To remove the last element - removeLast( ) or pollLast( ).
• First method gives exception on list empty, Second method
returns null or false
Collection implementation classes - Arraylist, linkedlist, Stack
LinkedList class
• Doubly-linked list implementation of the List
and Deque interfaces.
• Implements all optional list operations, and
permits all elements (including null).
• All of the operations perform as could be
expected for a doubly-linked list.
Collection implementation classes - Arraylist, linkedlist, Stack
Operations
• To create a LinkedList of String type:
LinkedList<String> llist=new LinkedList<String>();
• To add an element to a list:
llist.add(2,”Apple”); llist.add(”Apple”);
llist.addFirst(”Apple”); llist.addLast(”Apple”);
• To remove an element from the list:
llist.remove();
llist.remove(2); llist.remove(”Apple”);
llist.removeFirst(); llist.removeLast();
• To get the element from the list:
llist.get(3); llist.getFirst(); llist.getLast();
Operations
• To insert the specified element to a list: return boolean
llist.offer(“Mango”); llist.offerFirst(”Mango”);
llist.offerLast(”Mango”);
• To remove an element from the list: returns spl. Value
llist.poll(); llist.pollFirst(); llist.pollLast();
• To search an element from the list: returns spl. Value
llist.peek();llist.peekFirst(); llist.peekLast();
LinkedList
import java.util.*;
class LinkListTest
{
public static void main(String args[])
{
LinkedList<String> llist = new LinkedList<String>();
llist.add("Mango");
llist.add("Grapes");
llist.addLast("Orange");
System.out.println("Original List: "+llist);
llist.addFirst("Apple");
System.out.println("After addFirst: "+llist);
llist.add("Kiwi");
System.out.println("After add: "+llist);
System.out.println("Peek First: "+llist.peekFirst());
Original List: [Mango, Grapes, Orange]
After addFirst: [Apple, Mango, Grapes,
Orange]
After add: [Apple, Mango, Grapes, Orange, Kiwi]
Peek First: Apple
System.out.println(llist);
System.out.println("Poll Last: "+llist.pollLast());
System.out.println("Add Banana: “+llist.offerFirst("Banana"));
System.out.println("offFir, pollLast: "+llist);
llist.removeLast();
System.out.println("After removeLast: "+llist);
ListIterator<String> litr = llist.listIterator(2);
while(litr.hasNext()) {
String element = litr.next();
litr.set(element + "+");
}
System.out.println("Modified List: "+llist);
for(String s:llist)
{ System.out.print(s+”---”); }
} //main
}//class
[Apple, Mango, Grapes, Orange, Kiwi]
Poll Last: Kiwi
Add Banana: true
offFir, pollLast: [Banana, Apple, Mango,
Grapes, Orange]
After removeLast: [Banana, Apple,
Mango, Grapes]
Modified List: [Banana, Apple,
Mango+, Grapes+]
Banana---Apple---Mango+---Grapes+---
Iterator interface
• Use the Iterator object provided by each Collection
class, to access each element in the Collection.
• public interface Iterator<E>
• Steps to access collections via Iterator
– 1. Obtain an iterator to the start of the collection by
calling the collection’s iterator( ) method.
Iterator<E> iterator()
– 2. Set up a loop that makes a call to hasNext( ). Have the
loop iterate as long as hasNext( ) returns true.
– 3. Within the loop, obtain each element by calling next( ).
Collection implementation classes - Arraylist, linkedlist, Stack
ListIterator interface
• ListIterator is available only to those collections
that implement the List interface.
• For collections that implement List, obtain an
iterator by calling listIterator( )
• A listiterator has the ability to access the
collection in either the forward or backward
direction and allows to modify an element.
• public interface ListIterator<E> extends Iterator
<E>
Collection implementation classes - Arraylist, linkedlist, Stack
import java.util.*;
class ArrIter
{
public static void main(String args[])
{
ArrayList<String> al = new ArrayList<String>();
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
System.out.print("Original contents of al: ");
Iterator<String> itr = al.iterator();
while(itr.hasNext()) {
String element = itr.next();
System.out.print(element + " ");
}
Original contents of al: C A E B D F
System.out.println(“Original list”+al);
ListIterator<String> litr = al.listIterator();
while(litr.hasNext()) {
String element = litr.next();
litr.set(element + "+");
}
System.out.println(“Modified list ”+al);
System.out.print("Modified list backwards: ");
while(litr.hasPrevious()) {
String element = litr.previous();
System.out.print(element + " ");
}
} //main
} //class
Modified list [C+, A+, E+, B+, D+, F+]
Original list C A E B D F
Modified list backwards:
F+ D+ B+ E+ A+ C+
Collections Revisited
PriorityQueue Class
• public class PriorityQueue<E> extends AbstractQueue<E>
implements Serializable
• Dynamic queue
• PriorityQueue( )
• PriorityQueue(int capacity)
• PriorityQueue(int capacity, Comparator<? super E> comp) ---- default
comparator is ascending order, can define custom defined
comparator (timestamp)
• PriorityQueue(Collection<? extends E> c)
• PriorityQueue(PriorityQueue<? extends E> c)
• PriorityQueue(SortedSet<? extends E> c)
• Min Heap Storage by default
Collection implementation classes - Arraylist, linkedlist, Stack
PriorityQueue
import java.util.*;
public class PriorityQueueDemo {
public static void main(String args[])
{
// Creating an empty PriorityQueue
PriorityQueue<Integer> queue = new PriorityQueue<Integer>();
// Use add() method to add elements into the Queue
queue.add(10);
queue.add(15);
queue.add(30);
queue.add(20);
queue.add(5);
System.out.println("PriorityQueue: " + queue);
}
}
PriorityQueue: [5, 10, 30, 20, 15]
10,15,30,20,5
10 10
15
10
15 30
10
15 30
20
10
15 30
20 5
10
15
30
20
5
10
15
30
20
5
PriorityQueue
import java.util.*;
public class PriorityQueueDemo {
public static void main(String args[])
{
// Creating an empty PriorityQueue
PriorityQueue<Integer> queue = new PriorityQueue<Integer>();
// Use add() method to add elements into the Queue
queue.add(10);
queue.add(15);
queue.add(30);
queue.add(20);
queue.add(5);
queue.add(22);
queue.add(3);
queue.add(50);
queue.add(18);
System.out.println("PriorityQueue: " + queue);
}
}
PriorityQueue
import java.util.*;
public class PriorityQueueDemo {
public static void main(String args[])
{
// Creating an empty PriorityQueue
PriorityQueue<Integer> queue = new PriorityQueue<Integer>();
// Use add() method to add elements into the Queue
queue.add(10);
queue.add(15);
queue.add(30);
queue.add(20);
queue.add(5);
queue.add(22);
queue.add(3);
queue.add(50);
queue.add(18);
System.out.println("PriorityQueue: " + queue);
}
}
PriorityQueue: [3, 10, 5, 18, 15, 30, 22, 50, 20]
Operations
import java.util.*;
public class Example
{
public static void main(String args[])
{
// Creating empty priority queue
PriorityQueue<String> pQueue =
new PriorityQueue<String>();
// Adding items to the pQueue using add()
pQueue.add("C");
pQueue.add("Python");
pQueue.add("C++");
pQueue.add("Java");
System.out.println("Elements in Priority Queue : "+pQueue);
// Printing the most priority element
System.out.println("Head value using peek function:"
+ pQueue.peek());
// Printing all elements
System.out.println("The queue elements:");
Iterator itr = pQueue.iterator();
while (itr.hasNext())
System.out.println(itr.next());
Elements in Priority Queue :
[C, Java, C++, Python]
Head value using peek function:C
The queue elements:
C
Java
C++
Python
Operations
// Removing the top priority element (or head) and
// printing the modified pQueue using poll()
pQueue.poll();
System.out.println("After removing an element" +
"with poll function: " +pQueue);
// Removing Java using remove()
pQueue.remove("Java");
System.out.println("after removing Java with" +
" remove function: "+pQueue);
Iterator<String> itr3 = pQueue.iterator();
// Check if an element is present using contains()
boolean b = pQueue.contains("C");
System.out.println ( "Priority queue contains C " +
"or not?: " + b);
// Getting objects from the queue using toArray()
// in an array and print the array
Object[] arr = pQueue.toArray();
System.out.println ( "Value in array: ");
for (int i = 0; i<arr.length; i++)
System.out.println ( "Value: " + arr[i].toString()) ;
}
}
After removing an element with
poll function: [C++, Java, Python]
after removing Java with remove function:
[C++, Python]
Priority queue contains C or not?: false
Value in array:
Value: C++
Value: Python
TreeSet Class
• public class TreeSet<E> extends AbstractSet<E>
implements NavigableSet<E>, Cloneable,
Serializable
• It creates a collection that uses a tree for storage.
Objects are stored in sorted, ascending order.
• Access and retrieval times are quite fast, which
makes TreeSet an excellent choice when storing
large amounts of sorted information that must
be found quickly.
Collection implementation classes - Arraylist, linkedlist, Stack
Constructors
• TreeSet( )
• TreeSet(Collection<? extends E> c)
• TreeSet(Comparator<? super E> comp)
• TreeSet(SortedSet<E> ss)
• TreeSet implements the SortedSet interface so
duplicate values are not allowed.
TreeSet
import java.util.TreeSet;
public class TreeSetExample
{ public static void main(String args[]) {
// TreeSet of String Type
TreeSet<String> tset = new TreeSet<String>();
// Adding elements to TreeSet<String>
tset.add("ABC");
tset.add("String");
tset.add("Test");
tset.add("Pen");
tset.add("Ink");
tset.add("Jack");
tset.add("Pen"); // no error. Duplicate value is not inserted
//Displaying TreeSet
System.out.println(tset);
} }
[ABC, Ink, Jack, Pen, String, Test]
System.out.println(tset);
System.out.println("The first element is: " + tset.first());
// first element is removed
System.out.println("First lowest element " +
"removed is : " + tset.pollFirst()); //pollLast removes last highestelement
System.out.println("After removing element" +
" from TreeSet: " + tset);
System.out.println(tset.lower("SSN")); //< Pen
System.out.println(tset.lower("String")); //< Pen
System.out.println(tset.floor("String")); //<= String
System.out.println(tset.ceiling("String")); //>= String
System.out.println(tset.higher("String")); //> Test
System.out.println(tset.descendingSet()); // [Test, String, Pen, Jack, Ink]
System.out.println(tset.headSet("Pen")); // all elements < [Ink, Jack]
System.out.println(tset.tailSet("Pen")); //all elements >= [Pen, String, Test]
System.out.println(tset.subSet("Jack","String")); //[Jack, Pen]
[ABC, Ink, Jack, Pen, String, Test]
The first element is: ABC
First lowest element removed is : ABC
After removing element from TreeSet:
[Ink, Jack, Pen, String, Test]
References
• Herbert Schildt,“Java:The Complete
Reference”, 8th Edition,McGrawHill Education,
2011.
• https://docs.oracle.com/javase/7/docs/api/jav
a/util/
• https://visualgo.net/en/heap --- MaxHeap
Ad

Recommended

module2a it is module 2 so it is module 2.pptx
module2a it is module 2 so it is module 2.pptx
bharath555tth
 
Queue
Queue
Ayaz Akhtar
 
Collections in object oriented programming
Collections in object oriented programming
KaranAgrawal78
 
Ch03_stacks_and_queues.ppt
Ch03_stacks_and_queues.ppt
OliverKane3
 
Module-1 Updated Collection Framework.pptx
Module-1 Updated Collection Framework.pptx
rekhakeerti19
 
Collections
Collections
Rajkattamuri
 
Collections in Java
Collections in Java
Khasim Cise
 
Collections
Collections
Manav Prasad
 
In Python, a list is a built-in dynamic sized array. We can store all types o...
In Python, a list is a built-in dynamic sized array. We can store all types o...
Karthik Rohan
 
Collections Framework Beginners Guide 2
Collections Framework Beginners Guide 2
Kenji HASUNUMA
 
Collections Framework Begineers guide 2
Collections Framework Begineers guide 2
Kenji HASUNUMA
 
9 python data structure-2
9 python data structure-2
Prof. Dr. K. Adisesha
 
JAVA PROGRAMMING - The Collections Framework
JAVA PROGRAMMING - The Collections Framework
Jyothishmathi Institute of Technology and Science Karimnagar
 
Data Structure Using C
Data Structure Using C
CHANDERPRABHU JAIN COLLEGE OF HIGHER STUDIES & SCHOOL OF LAW
 
Collections - Lists & sets
Collections - Lists & sets
RatnaJava
 
Basic data-structures-v.1.1
Basic data-structures-v.1.1
BG Java EE Course
 
2 b queues
2 b queues
Nguync91368
 
Collections - Array List
Collections - Array List
Hitesh-Java
 
U-III-part-1.pptxpart 1 of Java and hardware coding questions are answered
U-III-part-1.pptxpart 1 of Java and hardware coding questions are answered
zainmkhan20
 
Lists
Lists
Sumit Tambe
 
standard template library(STL) in C++
standard template library(STL) in C++
•sreejith •sree
 
collections
collections
javeed_mhd
 
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
freddysarabia1
 
Lecture 1 Abstract Data Types of Complexity Analysis of Big Oh Notation.pptx
Lecture 1 Abstract Data Types of Complexity Analysis of Big Oh Notation.pptx
yhrcxd8wpm
 
Lecture 1 Abstract Data Types of Complexity Analysis of Big Oh Notation.pptx
Lecture 1 Abstract Data Types of Complexity Analysis of Big Oh Notation.pptx
yhrcxd8wpm
 
Collection
Collection
Gayathri Ganesh
 
Java ArrayList Tutorial | Edureka
Java ArrayList Tutorial | Edureka
Edureka!
 
12_-_Collections_Framework
12_-_Collections_Framework
Krishna Sujeer
 
ROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptx
ROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptx
Belicia R.S
 
ABCs of Bookkeeping for Nonprofits TechSoup.pdf
ABCs of Bookkeeping for Nonprofits TechSoup.pdf
TechSoup
 

More Related Content

Similar to Collection implementation classes - Arraylist, linkedlist, Stack (20)

In Python, a list is a built-in dynamic sized array. We can store all types o...
In Python, a list is a built-in dynamic sized array. We can store all types o...
Karthik Rohan
 
Collections Framework Beginners Guide 2
Collections Framework Beginners Guide 2
Kenji HASUNUMA
 
Collections Framework Begineers guide 2
Collections Framework Begineers guide 2
Kenji HASUNUMA
 
9 python data structure-2
9 python data structure-2
Prof. Dr. K. Adisesha
 
JAVA PROGRAMMING - The Collections Framework
JAVA PROGRAMMING - The Collections Framework
Jyothishmathi Institute of Technology and Science Karimnagar
 
Data Structure Using C
Data Structure Using C
CHANDERPRABHU JAIN COLLEGE OF HIGHER STUDIES & SCHOOL OF LAW
 
Collections - Lists & sets
Collections - Lists & sets
RatnaJava
 
Basic data-structures-v.1.1
Basic data-structures-v.1.1
BG Java EE Course
 
2 b queues
2 b queues
Nguync91368
 
Collections - Array List
Collections - Array List
Hitesh-Java
 
U-III-part-1.pptxpart 1 of Java and hardware coding questions are answered
U-III-part-1.pptxpart 1 of Java and hardware coding questions are answered
zainmkhan20
 
Lists
Lists
Sumit Tambe
 
standard template library(STL) in C++
standard template library(STL) in C++
•sreejith •sree
 
collections
collections
javeed_mhd
 
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
freddysarabia1
 
Lecture 1 Abstract Data Types of Complexity Analysis of Big Oh Notation.pptx
Lecture 1 Abstract Data Types of Complexity Analysis of Big Oh Notation.pptx
yhrcxd8wpm
 
Lecture 1 Abstract Data Types of Complexity Analysis of Big Oh Notation.pptx
Lecture 1 Abstract Data Types of Complexity Analysis of Big Oh Notation.pptx
yhrcxd8wpm
 
Collection
Collection
Gayathri Ganesh
 
Java ArrayList Tutorial | Edureka
Java ArrayList Tutorial | Edureka
Edureka!
 
12_-_Collections_Framework
12_-_Collections_Framework
Krishna Sujeer
 
In Python, a list is a built-in dynamic sized array. We can store all types o...
In Python, a list is a built-in dynamic sized array. We can store all types o...
Karthik Rohan
 
Collections Framework Beginners Guide 2
Collections Framework Beginners Guide 2
Kenji HASUNUMA
 
Collections Framework Begineers guide 2
Collections Framework Begineers guide 2
Kenji HASUNUMA
 
Collections - Lists & sets
Collections - Lists & sets
RatnaJava
 
Collections - Array List
Collections - Array List
Hitesh-Java
 
U-III-part-1.pptxpart 1 of Java and hardware coding questions are answered
U-III-part-1.pptxpart 1 of Java and hardware coding questions are answered
zainmkhan20
 
standard template library(STL) in C++
standard template library(STL) in C++
•sreejith •sree
 
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
freddysarabia1
 
Lecture 1 Abstract Data Types of Complexity Analysis of Big Oh Notation.pptx
Lecture 1 Abstract Data Types of Complexity Analysis of Big Oh Notation.pptx
yhrcxd8wpm
 
Lecture 1 Abstract Data Types of Complexity Analysis of Big Oh Notation.pptx
Lecture 1 Abstract Data Types of Complexity Analysis of Big Oh Notation.pptx
yhrcxd8wpm
 
Java ArrayList Tutorial | Edureka
Java ArrayList Tutorial | Edureka
Edureka!
 
12_-_Collections_Framework
12_-_Collections_Framework
Krishna Sujeer
 

Recently uploaded (20)

ROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptx
ROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptx
Belicia R.S
 
ABCs of Bookkeeping for Nonprofits TechSoup.pdf
ABCs of Bookkeeping for Nonprofits TechSoup.pdf
TechSoup
 
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
Sourav Kr Podder
 
How to Manage Inventory Movement in Odoo 18 POS
How to Manage Inventory Movement in Odoo 18 POS
Celine George
 
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Rajdeep Bavaliya
 
Non-Communicable Diseases and National Health Programs – Unit 10 | B.Sc Nursi...
Non-Communicable Diseases and National Health Programs – Unit 10 | B.Sc Nursi...
RAKESH SAJJAN
 
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
jutaydeonne
 
“THE BEST CLASS IN SCHOOL”. _
“THE BEST CLASS IN SCHOOL”. _
Colégio Santa Teresinha
 
How to Manage Different Customer Addresses in Odoo 18 Accounting
How to Manage Different Customer Addresses in Odoo 18 Accounting
Celine George
 
Assisting Individuals and Families to Promote and Maintain Health – Unit 7 | ...
Assisting Individuals and Families to Promote and Maintain Health – Unit 7 | ...
RAKESH SAJJAN
 
Health Care Planning and Organization of Health Care at Various Levels – Unit...
Health Care Planning and Organization of Health Care at Various Levels – Unit...
RAKESH SAJJAN
 
What is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
Q1_ENGLISH_PPT_WEEK 1 power point grade 3 Quarter 1 week 1
Q1_ENGLISH_PPT_WEEK 1 power point grade 3 Quarter 1 week 1
jutaydeonne
 
LDMMIA Practitioner Student Reiki Yoga S2 Video PDF Without Yogi Goddess
LDMMIA Practitioner Student Reiki Yoga S2 Video PDF Without Yogi Goddess
LDM & Mia eStudios
 
2025 June Year 9 Presentation: Subject selection.pptx
2025 June Year 9 Presentation: Subject selection.pptx
mansk2
 
LAZY SUNDAY QUIZ "A GENERAL QUIZ" JUNE 2025 SMC QUIZ CLUB, SILCHAR MEDICAL CO...
LAZY SUNDAY QUIZ "A GENERAL QUIZ" JUNE 2025 SMC QUIZ CLUB, SILCHAR MEDICAL CO...
Ultimatewinner0342
 
LDM Recording Presents Yogi Goddess by LDMMIA
LDM Recording Presents Yogi Goddess by LDMMIA
LDM & Mia eStudios
 
Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...
Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...
Rajdeep Bavaliya
 
Pests of Maize: An comprehensive overview.pptx
Pests of Maize: An comprehensive overview.pptx
Arshad Shaikh
 
ROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptx
ROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptx
Belicia R.S
 
ABCs of Bookkeeping for Nonprofits TechSoup.pdf
ABCs of Bookkeeping for Nonprofits TechSoup.pdf
TechSoup
 
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
Sourav Kr Podder
 
How to Manage Inventory Movement in Odoo 18 POS
How to Manage Inventory Movement in Odoo 18 POS
Celine George
 
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Rajdeep Bavaliya
 
Non-Communicable Diseases and National Health Programs – Unit 10 | B.Sc Nursi...
Non-Communicable Diseases and National Health Programs – Unit 10 | B.Sc Nursi...
RAKESH SAJJAN
 
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
jutaydeonne
 
How to Manage Different Customer Addresses in Odoo 18 Accounting
How to Manage Different Customer Addresses in Odoo 18 Accounting
Celine George
 
Assisting Individuals and Families to Promote and Maintain Health – Unit 7 | ...
Assisting Individuals and Families to Promote and Maintain Health – Unit 7 | ...
RAKESH SAJJAN
 
Health Care Planning and Organization of Health Care at Various Levels – Unit...
Health Care Planning and Organization of Health Care at Various Levels – Unit...
RAKESH SAJJAN
 
What is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
Q1_ENGLISH_PPT_WEEK 1 power point grade 3 Quarter 1 week 1
Q1_ENGLISH_PPT_WEEK 1 power point grade 3 Quarter 1 week 1
jutaydeonne
 
LDMMIA Practitioner Student Reiki Yoga S2 Video PDF Without Yogi Goddess
LDMMIA Practitioner Student Reiki Yoga S2 Video PDF Without Yogi Goddess
LDM & Mia eStudios
 
2025 June Year 9 Presentation: Subject selection.pptx
2025 June Year 9 Presentation: Subject selection.pptx
mansk2
 
LAZY SUNDAY QUIZ "A GENERAL QUIZ" JUNE 2025 SMC QUIZ CLUB, SILCHAR MEDICAL CO...
LAZY SUNDAY QUIZ "A GENERAL QUIZ" JUNE 2025 SMC QUIZ CLUB, SILCHAR MEDICAL CO...
Ultimatewinner0342
 
LDM Recording Presents Yogi Goddess by LDMMIA
LDM Recording Presents Yogi Goddess by LDMMIA
LDM & Mia eStudios
 
Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...
Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...
Rajdeep Bavaliya
 
Pests of Maize: An comprehensive overview.pptx
Pests of Maize: An comprehensive overview.pptx
Arshad Shaikh
 
Ad

Collection implementation classes - Arraylist, linkedlist, Stack

  • 2. Learning Outcome • Understand the working and methods in classes – ArrayList – LinkedList – Queue – Set – Trees • Interfaces – Iterator – ListIterator
  • 3. Collection class- ArrayList • ArrayList supports dynamic arrays that can grow as needed • ArrayList is a variable-length array of object references. • An ArrayList can dynamically increase or decrease insize. • Array lists are created with an initial size • When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array can be shrunk. • public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable
  • 5. ArrayList- methods • ArrayList( ) • ArrayList(Collection<? extends E> c) • ArrayList(int capacity) • void ensureCapacity(int cap) – to increase capacity manually to avoid reallocations • void trimToSize( ) – to reduce size manually • object[ ] toArray( ) • <T> T[ ] toArray(T array[ ])
  • 6. Original List: [India, China, US, Germany, Bhutan] After add: [India, China, US, SriLanka, Germany, Bhutan] After remove: [India, US, SriLanka, Bhutan] alist.size()  0 alist.size()  5 ArrayList
  • 7. After Sort: [Bhutan, India, SriLanka, US] After reverse: [US, SriLanka, India, Bhutan] Using get(): India After subList: [SriLanka, India] After set: [Nepal, India] After Combine: [US, SriLanka, India, Bhutan, Nepal, India]
  • 8. For loop – iterated through List for(String v : alist) { System.out.print(v + “*** "); } US *** SriLanka*** India***Bhutan***Nepal***India
  • 9. Storing user defined class in ArrayList import java.util.*; class Book { private String title; private int price; Book(String title, int price) { this.title=title; this.price=price; } @Override public String toString() { return "Title is: "+this.title+"n" +" Price is: "+this.price; } }
  • 10. Storing user defined class in ArrayList class BookList { public static void main(String args[]) { ArrayList<Book> al= new ArrayList<Book>(); al.add(new Book("Java Fundamentals", 340)); al.add(new Book("Data Structure", 140)); al.add(new Book("Python Programming", 320)); for (Book tmp: al) System.out.println(tmp); } }
  • 11. Output: Title is: Java Fundamentals Price is: 340 Title is: Data Structure Price is: 140 Title is: Python Programming Price is: 320
  • 12. Linked List class • public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, Serializable • LinkedList( ) • LinkedList(Collection<? extends E> c) • To add elements to the start of list - addFirst( ) or offerFirst( ). • To add elements to the end of list - addLast( ) or offerLast( ). • To obtain the first element - getFirst( ) or peekFirst( ). • To obtain the last element - getLast( ) or peekLast( ). • To remove the first element - removeFirst( ) or pollFirst( ). • To remove the last element - removeLast( ) or pollLast( ). • First method gives exception on list empty, Second method returns null or false
  • 14. LinkedList class • Doubly-linked list implementation of the List and Deque interfaces. • Implements all optional list operations, and permits all elements (including null). • All of the operations perform as could be expected for a doubly-linked list.
  • 16. Operations • To create a LinkedList of String type: LinkedList<String> llist=new LinkedList<String>(); • To add an element to a list: llist.add(2,”Apple”); llist.add(”Apple”); llist.addFirst(”Apple”); llist.addLast(”Apple”); • To remove an element from the list: llist.remove(); llist.remove(2); llist.remove(”Apple”); llist.removeFirst(); llist.removeLast(); • To get the element from the list: llist.get(3); llist.getFirst(); llist.getLast();
  • 17. Operations • To insert the specified element to a list: return boolean llist.offer(“Mango”); llist.offerFirst(”Mango”); llist.offerLast(”Mango”); • To remove an element from the list: returns spl. Value llist.poll(); llist.pollFirst(); llist.pollLast(); • To search an element from the list: returns spl. Value llist.peek();llist.peekFirst(); llist.peekLast();
  • 18. LinkedList import java.util.*; class LinkListTest { public static void main(String args[]) { LinkedList<String> llist = new LinkedList<String>(); llist.add("Mango"); llist.add("Grapes"); llist.addLast("Orange"); System.out.println("Original List: "+llist); llist.addFirst("Apple"); System.out.println("After addFirst: "+llist); llist.add("Kiwi"); System.out.println("After add: "+llist); System.out.println("Peek First: "+llist.peekFirst()); Original List: [Mango, Grapes, Orange] After addFirst: [Apple, Mango, Grapes, Orange] After add: [Apple, Mango, Grapes, Orange, Kiwi] Peek First: Apple
  • 19. System.out.println(llist); System.out.println("Poll Last: "+llist.pollLast()); System.out.println("Add Banana: “+llist.offerFirst("Banana")); System.out.println("offFir, pollLast: "+llist); llist.removeLast(); System.out.println("After removeLast: "+llist); ListIterator<String> litr = llist.listIterator(2); while(litr.hasNext()) { String element = litr.next(); litr.set(element + "+"); } System.out.println("Modified List: "+llist); for(String s:llist) { System.out.print(s+”---”); } } //main }//class [Apple, Mango, Grapes, Orange, Kiwi] Poll Last: Kiwi Add Banana: true offFir, pollLast: [Banana, Apple, Mango, Grapes, Orange] After removeLast: [Banana, Apple, Mango, Grapes] Modified List: [Banana, Apple, Mango+, Grapes+] Banana---Apple---Mango+---Grapes+---
  • 20. Iterator interface • Use the Iterator object provided by each Collection class, to access each element in the Collection. • public interface Iterator<E> • Steps to access collections via Iterator – 1. Obtain an iterator to the start of the collection by calling the collection’s iterator( ) method. Iterator<E> iterator() – 2. Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true. – 3. Within the loop, obtain each element by calling next( ).
  • 22. ListIterator interface • ListIterator is available only to those collections that implement the List interface. • For collections that implement List, obtain an iterator by calling listIterator( ) • A listiterator has the ability to access the collection in either the forward or backward direction and allows to modify an element. • public interface ListIterator<E> extends Iterator <E>
  • 24. import java.util.*; class ArrIter { public static void main(String args[]) { ArrayList<String> al = new ArrayList<String>(); al.add("C"); al.add("A"); al.add("E"); al.add("B"); al.add("D"); al.add("F"); System.out.print("Original contents of al: "); Iterator<String> itr = al.iterator(); while(itr.hasNext()) { String element = itr.next(); System.out.print(element + " "); } Original contents of al: C A E B D F
  • 25. System.out.println(“Original list”+al); ListIterator<String> litr = al.listIterator(); while(litr.hasNext()) { String element = litr.next(); litr.set(element + "+"); } System.out.println(“Modified list ”+al); System.out.print("Modified list backwards: "); while(litr.hasPrevious()) { String element = litr.previous(); System.out.print(element + " "); } } //main } //class Modified list [C+, A+, E+, B+, D+, F+] Original list C A E B D F Modified list backwards: F+ D+ B+ E+ A+ C+
  • 27. PriorityQueue Class • public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable • Dynamic queue • PriorityQueue( ) • PriorityQueue(int capacity) • PriorityQueue(int capacity, Comparator<? super E> comp) ---- default comparator is ascending order, can define custom defined comparator (timestamp) • PriorityQueue(Collection<? extends E> c) • PriorityQueue(PriorityQueue<? extends E> c) • PriorityQueue(SortedSet<? extends E> c) • Min Heap Storage by default
  • 29. PriorityQueue import java.util.*; public class PriorityQueueDemo { public static void main(String args[]) { // Creating an empty PriorityQueue PriorityQueue<Integer> queue = new PriorityQueue<Integer>(); // Use add() method to add elements into the Queue queue.add(10); queue.add(15); queue.add(30); queue.add(20); queue.add(5); System.out.println("PriorityQueue: " + queue); } } PriorityQueue: [5, 10, 30, 20, 15]
  • 30. 10,15,30,20,5 10 10 15 10 15 30 10 15 30 20 10 15 30 20 5 10 15 30 20 5 10 15 30 20 5
  • 31. PriorityQueue import java.util.*; public class PriorityQueueDemo { public static void main(String args[]) { // Creating an empty PriorityQueue PriorityQueue<Integer> queue = new PriorityQueue<Integer>(); // Use add() method to add elements into the Queue queue.add(10); queue.add(15); queue.add(30); queue.add(20); queue.add(5); queue.add(22); queue.add(3); queue.add(50); queue.add(18); System.out.println("PriorityQueue: " + queue); } }
  • 32. PriorityQueue import java.util.*; public class PriorityQueueDemo { public static void main(String args[]) { // Creating an empty PriorityQueue PriorityQueue<Integer> queue = new PriorityQueue<Integer>(); // Use add() method to add elements into the Queue queue.add(10); queue.add(15); queue.add(30); queue.add(20); queue.add(5); queue.add(22); queue.add(3); queue.add(50); queue.add(18); System.out.println("PriorityQueue: " + queue); } } PriorityQueue: [3, 10, 5, 18, 15, 30, 22, 50, 20]
  • 33. Operations import java.util.*; public class Example { public static void main(String args[]) { // Creating empty priority queue PriorityQueue<String> pQueue = new PriorityQueue<String>(); // Adding items to the pQueue using add() pQueue.add("C"); pQueue.add("Python"); pQueue.add("C++"); pQueue.add("Java"); System.out.println("Elements in Priority Queue : "+pQueue); // Printing the most priority element System.out.println("Head value using peek function:" + pQueue.peek()); // Printing all elements System.out.println("The queue elements:"); Iterator itr = pQueue.iterator(); while (itr.hasNext()) System.out.println(itr.next()); Elements in Priority Queue : [C, Java, C++, Python] Head value using peek function:C The queue elements: C Java C++ Python
  • 34. Operations // Removing the top priority element (or head) and // printing the modified pQueue using poll() pQueue.poll(); System.out.println("After removing an element" + "with poll function: " +pQueue); // Removing Java using remove() pQueue.remove("Java"); System.out.println("after removing Java with" + " remove function: "+pQueue); Iterator<String> itr3 = pQueue.iterator(); // Check if an element is present using contains() boolean b = pQueue.contains("C"); System.out.println ( "Priority queue contains C " + "or not?: " + b); // Getting objects from the queue using toArray() // in an array and print the array Object[] arr = pQueue.toArray(); System.out.println ( "Value in array: "); for (int i = 0; i<arr.length; i++) System.out.println ( "Value: " + arr[i].toString()) ; } } After removing an element with poll function: [C++, Java, Python] after removing Java with remove function: [C++, Python] Priority queue contains C or not?: false Value in array: Value: C++ Value: Python
  • 35. TreeSet Class • public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>, Cloneable, Serializable • It creates a collection that uses a tree for storage. Objects are stored in sorted, ascending order. • Access and retrieval times are quite fast, which makes TreeSet an excellent choice when storing large amounts of sorted information that must be found quickly.
  • 37. Constructors • TreeSet( ) • TreeSet(Collection<? extends E> c) • TreeSet(Comparator<? super E> comp) • TreeSet(SortedSet<E> ss) • TreeSet implements the SortedSet interface so duplicate values are not allowed.
  • 38. TreeSet import java.util.TreeSet; public class TreeSetExample { public static void main(String args[]) { // TreeSet of String Type TreeSet<String> tset = new TreeSet<String>(); // Adding elements to TreeSet<String> tset.add("ABC"); tset.add("String"); tset.add("Test"); tset.add("Pen"); tset.add("Ink"); tset.add("Jack"); tset.add("Pen"); // no error. Duplicate value is not inserted //Displaying TreeSet System.out.println(tset); } } [ABC, Ink, Jack, Pen, String, Test]
  • 39. System.out.println(tset); System.out.println("The first element is: " + tset.first()); // first element is removed System.out.println("First lowest element " + "removed is : " + tset.pollFirst()); //pollLast removes last highestelement System.out.println("After removing element" + " from TreeSet: " + tset); System.out.println(tset.lower("SSN")); //< Pen System.out.println(tset.lower("String")); //< Pen System.out.println(tset.floor("String")); //<= String System.out.println(tset.ceiling("String")); //>= String System.out.println(tset.higher("String")); //> Test System.out.println(tset.descendingSet()); // [Test, String, Pen, Jack, Ink] System.out.println(tset.headSet("Pen")); // all elements < [Ink, Jack] System.out.println(tset.tailSet("Pen")); //all elements >= [Pen, String, Test] System.out.println(tset.subSet("Jack","String")); //[Jack, Pen] [ABC, Ink, Jack, Pen, String, Test] The first element is: ABC First lowest element removed is : ABC After removing element from TreeSet: [Ink, Jack, Pen, String, Test]
  • 40. References • Herbert Schildt,“Java:The Complete Reference”, 8th Edition,McGrawHill Education, 2011. • https://docs.oracle.com/javase/7/docs/api/jav a/util/ • https://visualgo.net/en/heap --- MaxHeap