SlideShare ist ein Scribd-Unternehmen logo
1 von 21
Java/J2EE Programming Training
Collections
Page 2Classification: Restricted
Agenda
• Recap of Arrays
• Introduction to Collections API
• Lists – ArrayList, Vector, LinkedList
Arrays…
Classification: Restricted Page 3
• How are arrays defined?
int[] myArray = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
int[] myArray = new int[10];
myArray[0] = 2;
myArray[1] = 5; …
• Iterating through array: Use for loop
• Sort and search: Use java.util.Arrays
• Demo of arrays…
Major shortcoming of arrays?
Classification: Restricted Page 4
• Length of arrays is fixed when the array is created. It cannot be changed
after that.
• The solution is to use one of the List classes from the Collections API.
• PROGRAM = DATA STRUCTURE + ALGORITHM;
Readings and References
Classification: Restricted Page 6
• References
• "Collections", Java tutorial
• http://java.sun.com/docs/books/tutorial/collections/index.html
Collections Framework
Classification: Restricted Page 7
• Unified architecture for representing and manipulating
collections.
• A collections framework contains three things
• Interfaces
• Implementations
• Algorithms
Collections Framework Diagram
Classification: Restricted Page 8
Collection Interface
Classification: Restricted Page 9
• Defines fundamental methods
•int size();
•boolean isEmpty();
•boolean contains(Object element);
•boolean add(Object element);
•boolean remove(Object element);
•Iterator iterator();
• These methods are enough to define the basic behavior of a
collection
• Provides an Iterator to step through the elements in the Collection
Iterator Interface
Classification: Restricted Page 10
• Defines three fundamental methods
•Object next()
•boolean hasNext()
•void remove()
• These three methods provide access to the contents of the
collection
• An Iterator knows position within collection
• Each call to next() “reads” an element from the collection
•Then you can use it or remove it
Iterator Position
Classification: Restricted Page 11
Example - SimpleCollection
Classification: Restricted Page 12
public class SimpleCollection {
public static void main(String[] args) {
Collection c;
c = new ArrayList();
System.out.println(c.getClass().getName()); for (int
i=1; i <= 10; i++) {
c.add(i + " * " + i + " = "+i*i);
}
Iterator iter = c.iterator(); while
(iter.hasNext())
System.out.println(iter.next());
}
}
List Interface Context
Classification: Restricted Page 13
Collection
List
ArrayList and LinkedList Context
ArrayList LinkedList
Classification: Restricted Page 14
Collection
List
List as part of Collection
Classification: Restricted Page 15
List Implementations
Classification: Restricted Page 16
• ArrayList
• low cost random access
• high cost insert and delete
• array that resizes if need be
• LinkedList
• sequential access
• low cost insert and delete
• high cost random access
• Vector
• Similar to ArrayList, but thread-safe
ArrayList overview
Classification: Restricted Page 17
• Constant time positional access (it’s an array)
• One tuning parameter, the initial capacity
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException(
"Illegal Capacity: "+initialCapacity);
this.elementData = new Object[initialCapacity];
}
ArrayList methods
Classification: Restricted Page 18
• The indexed get and set methods of the List interface are
appropriate to use since ArrayLists are backed by an array
•Object get(int index)
•Object set(int index, Object element)
• Indexed add and remove are provided, but can be costly if used
frequently
•void add(int index, Object element)
•Object remove(int index)
• May want to resize in one shot if adding many elements
•void ensureCapacity(int minCapacity)
Example: ArrayList
Classification: Restricted Page 19
ArrayList al = new ArrayList();
al.add(3);
al.add(2);
al.add(1);
al.add(4);
al.add(5);
al.add(6);
al.add(6);
Iterator iter1 = al.iterator();
while(iter1.hasNext()){
System.out.println(iter1.next());
}
Example: ArrayList (Using Generics + Iterating using Iterator
and for-each loop)
Classification: Restricted Page 20
import java.util.*; class
TestCollection1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
//Traversing using for-each loop
for(String obj:list)
System.out.println(obj);
}
User-defined class objects in Java ArrayList
Classification: Restricted Page 21
class Student{
int rollno;
String
name; int
age;
Student(int rollno,String name,int
age){ this.rollno=rollno;
this.name=name
; this.age=age;
}
}
import java.util.*;
public class TestCollection3{
public static void main(String args[]){
//Creating user-defined class objects Student
s1=new Student(101,"Sonoo",23); Student s2=new
Student(102,"Ravi",21);
Student s3=new Student(103,"Hanumat",25);
//creating arraylist
ArrayList<Student> al=new ArrayList<Student>();
al.add(s1);//adding Student class object al.add(s2);
al.add(s3);
//Getting Iterator Iterator
itr=al.iterator();
//traversing elements of ArrayList object
while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st.rollno+" "+st.name+"
"+st.age);
}
}
Thank You

Weitere ähnliche Inhalte

Was ist angesagt?

Java Collections Framework Inroduction with Video Tutorial
Java Collections Framework Inroduction with Video TutorialJava Collections Framework Inroduction with Video Tutorial
Java Collections Framework Inroduction with Video TutorialMarcus Biel
 
Session 14 - Object Class
Session 14 - Object ClassSession 14 - Object Class
Session 14 - Object ClassPawanMM
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in javaCPD INDIA
 
Array vs array list
Array vs array listArray vs array list
Array vs array listRavi Shetye
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & setsRatnaJava
 
5 collection framework
5 collection framework5 collection framework
5 collection frameworkMinal Maniar
 
The map interface (the java™ tutorials collections interfaces)
The map interface (the java™ tutorials   collections   interfaces)The map interface (the java™ tutorials   collections   interfaces)
The map interface (the java™ tutorials collections interfaces)charan kumar
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections frameworkRiccardo Cardin
 
JAVA Collections frame work ppt
 JAVA Collections frame work ppt JAVA Collections frame work ppt
JAVA Collections frame work pptRanjith Alappadan
 
C# Non generics collection
C# Non generics collectionC# Non generics collection
C# Non generics collectionPrem Kumar Badri
 
Java ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaJava ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaEdureka!
 
collection framework in java
collection framework in javacollection framework in java
collection framework in javaMANOJ KUMAR
 
Collections - Sorting, Comparing Basics
Collections - Sorting, Comparing Basics Collections - Sorting, Comparing Basics
Collections - Sorting, Comparing Basics Hitesh-Java
 
Java collections
Java collectionsJava collections
Java collectionsSujit Kumar
 

Was ist angesagt? (20)

Object Class
Object Class Object Class
Object Class
 
Java Collections Framework Inroduction with Video Tutorial
Java Collections Framework Inroduction with Video TutorialJava Collections Framework Inroduction with Video Tutorial
Java Collections Framework Inroduction with Video Tutorial
 
Java collection
Java collectionJava collection
Java collection
 
Session 14 - Object Class
Session 14 - Object ClassSession 14 - Object Class
Session 14 - Object Class
 
Collections framework in java
Collections framework in javaCollections framework in java
Collections framework in java
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
 
Array vs array list
Array vs array listArray vs array list
Array vs array list
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & sets
 
5 collection framework
5 collection framework5 collection framework
5 collection framework
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
 
The map interface (the java™ tutorials collections interfaces)
The map interface (the java™ tutorials   collections   interfaces)The map interface (the java™ tutorials   collections   interfaces)
The map interface (the java™ tutorials collections interfaces)
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
 
JAVA Collections frame work ppt
 JAVA Collections frame work ppt JAVA Collections frame work ppt
JAVA Collections frame work ppt
 
C# Non generics collection
C# Non generics collectionC# Non generics collection
C# Non generics collection
 
Java ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaJava ArrayList Tutorial | Edureka
Java ArrayList Tutorial | Edureka
 
collection framework in java
collection framework in javacollection framework in java
collection framework in java
 
Collections - Sorting, Comparing Basics
Collections - Sorting, Comparing Basics Collections - Sorting, Comparing Basics
Collections - Sorting, Comparing Basics
 
Java collections
Java collectionsJava collections
Java collections
 
Java collections notes
Java collections notesJava collections notes
Java collections notes
 

Ähnlich wie Collections Array list (20)

Collection framework
Collection frameworkCollection framework
Collection framework
 
Collections Training
Collections TrainingCollections Training
Collections Training
 
collection framework.pptx
collection framework.pptxcollection framework.pptx
collection framework.pptx
 
Java Collection
Java CollectionJava Collection
Java Collection
 
12_-_Collections_Framework
12_-_Collections_Framework12_-_Collections_Framework
12_-_Collections_Framework
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Collections
CollectionsCollections
Collections
 
Collections in java
Collections in javaCollections in java
Collections in java
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
Java util
Java utilJava util
Java util
 
Collections
CollectionsCollections
Collections
 
22.ppt
22.ppt22.ppt
22.ppt
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
 
Collection framework
Collection frameworkCollection framework
Collection framework
 
Collections lecture 35 40
Collections lecture 35 40Collections lecture 35 40
Collections lecture 35 40
 
STRINGS IN JAVA
STRINGS IN JAVASTRINGS IN JAVA
STRINGS IN JAVA
 
ArrayList in JAVA
ArrayList in JAVAArrayList in JAVA
ArrayList in JAVA
 
ArrayList in JAVA
ArrayList in JAVAArrayList in JAVA
ArrayList in JAVA
 
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
 
Java Unit 2 (Part 2)
Java Unit 2 (Part 2)Java Unit 2 (Part 2)
Java Unit 2 (Part 2)
 

Mehr von RatnaJava

Review Session and Attending Java Interviews
Review Session and Attending Java InterviewsReview Session and Attending Java Interviews
Review Session and Attending Java InterviewsRatnaJava
 
Collections - Sorting, Comparing Basics
Collections - Sorting, Comparing BasicsCollections - Sorting, Comparing Basics
Collections - Sorting, Comparing BasicsRatnaJava
 
Object Class
Object ClassObject Class
Object ClassRatnaJava
 
Exception Handling
Exception Handling  Exception Handling
Exception Handling RatnaJava
 
OOPs with Java - Packaging and Access Modifiers
OOPs with Java - Packaging and Access ModifiersOOPs with Java - Packaging and Access Modifiers
OOPs with Java - Packaging and Access ModifiersRatnaJava
 
OOP with Java - Abstract Classes and Interfaces
OOP with Java - Abstract Classes and InterfacesOOP with Java - Abstract Classes and Interfaces
OOP with Java - Abstract Classes and InterfacesRatnaJava
 
OOP with Java - Part 3
OOP with Java - Part 3OOP with Java - Part 3
OOP with Java - Part 3RatnaJava
 
OOP with Java - continued
OOP with Java - continuedOOP with Java - continued
OOP with Java - continuedRatnaJava
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented ProgrammingRatnaJava
 
Data Handling and Function
Data Handling and FunctionData Handling and Function
Data Handling and FunctionRatnaJava
 
Introduction to Java Part-3
Introduction to Java Part-3Introduction to Java Part-3
Introduction to Java Part-3RatnaJava
 
Introduction to Java Part-2
Introduction to Java Part-2Introduction to Java Part-2
Introduction to Java Part-2RatnaJava
 
Introduction to Java
Introduction to Java Introduction to Java
Introduction to Java RatnaJava
 

Mehr von RatnaJava (13)

Review Session and Attending Java Interviews
Review Session and Attending Java InterviewsReview Session and Attending Java Interviews
Review Session and Attending Java Interviews
 
Collections - Sorting, Comparing Basics
Collections - Sorting, Comparing BasicsCollections - Sorting, Comparing Basics
Collections - Sorting, Comparing Basics
 
Object Class
Object ClassObject Class
Object Class
 
Exception Handling
Exception Handling  Exception Handling
Exception Handling
 
OOPs with Java - Packaging and Access Modifiers
OOPs with Java - Packaging and Access ModifiersOOPs with Java - Packaging and Access Modifiers
OOPs with Java - Packaging and Access Modifiers
 
OOP with Java - Abstract Classes and Interfaces
OOP with Java - Abstract Classes and InterfacesOOP with Java - Abstract Classes and Interfaces
OOP with Java - Abstract Classes and Interfaces
 
OOP with Java - Part 3
OOP with Java - Part 3OOP with Java - Part 3
OOP with Java - Part 3
 
OOP with Java - continued
OOP with Java - continuedOOP with Java - continued
OOP with Java - continued
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
 
Data Handling and Function
Data Handling and FunctionData Handling and Function
Data Handling and Function
 
Introduction to Java Part-3
Introduction to Java Part-3Introduction to Java Part-3
Introduction to Java Part-3
 
Introduction to Java Part-2
Introduction to Java Part-2Introduction to Java Part-2
Introduction to Java Part-2
 
Introduction to Java
Introduction to Java Introduction to Java
Introduction to Java
 

Kürzlich hochgeladen

Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 

Kürzlich hochgeladen (20)

Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 

Collections Array list

  • 2. Page 2Classification: Restricted Agenda • Recap of Arrays • Introduction to Collections API • Lists – ArrayList, Vector, LinkedList
  • 3. Arrays… Classification: Restricted Page 3 • How are arrays defined? int[] myArray = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 }; int[] myArray = new int[10]; myArray[0] = 2; myArray[1] = 5; … • Iterating through array: Use for loop • Sort and search: Use java.util.Arrays • Demo of arrays…
  • 4. Major shortcoming of arrays? Classification: Restricted Page 4 • Length of arrays is fixed when the array is created. It cannot be changed after that. • The solution is to use one of the List classes from the Collections API. • PROGRAM = DATA STRUCTURE + ALGORITHM;
  • 5. Readings and References Classification: Restricted Page 6 • References • "Collections", Java tutorial • http://java.sun.com/docs/books/tutorial/collections/index.html
  • 6. Collections Framework Classification: Restricted Page 7 • Unified architecture for representing and manipulating collections. • A collections framework contains three things • Interfaces • Implementations • Algorithms
  • 8. Collection Interface Classification: Restricted Page 9 • Defines fundamental methods •int size(); •boolean isEmpty(); •boolean contains(Object element); •boolean add(Object element); •boolean remove(Object element); •Iterator iterator(); • These methods are enough to define the basic behavior of a collection • Provides an Iterator to step through the elements in the Collection
  • 9. Iterator Interface Classification: Restricted Page 10 • Defines three fundamental methods •Object next() •boolean hasNext() •void remove() • These three methods provide access to the contents of the collection • An Iterator knows position within collection • Each call to next() “reads” an element from the collection •Then you can use it or remove it
  • 11. Example - SimpleCollection Classification: Restricted Page 12 public class SimpleCollection { public static void main(String[] args) { Collection c; c = new ArrayList(); System.out.println(c.getClass().getName()); for (int i=1; i <= 10; i++) { c.add(i + " * " + i + " = "+i*i); } Iterator iter = c.iterator(); while (iter.hasNext()) System.out.println(iter.next()); } }
  • 12. List Interface Context Classification: Restricted Page 13 Collection List
  • 13. ArrayList and LinkedList Context ArrayList LinkedList Classification: Restricted Page 14 Collection List
  • 14. List as part of Collection Classification: Restricted Page 15
  • 15. List Implementations Classification: Restricted Page 16 • ArrayList • low cost random access • high cost insert and delete • array that resizes if need be • LinkedList • sequential access • low cost insert and delete • high cost random access • Vector • Similar to ArrayList, but thread-safe
  • 16. ArrayList overview Classification: Restricted Page 17 • Constant time positional access (it’s an array) • One tuning parameter, the initial capacity public ArrayList(int initialCapacity) { super(); if (initialCapacity < 0) throw new IllegalArgumentException( "Illegal Capacity: "+initialCapacity); this.elementData = new Object[initialCapacity]; }
  • 17. ArrayList methods Classification: Restricted Page 18 • The indexed get and set methods of the List interface are appropriate to use since ArrayLists are backed by an array •Object get(int index) •Object set(int index, Object element) • Indexed add and remove are provided, but can be costly if used frequently •void add(int index, Object element) •Object remove(int index) • May want to resize in one shot if adding many elements •void ensureCapacity(int minCapacity)
  • 18. Example: ArrayList Classification: Restricted Page 19 ArrayList al = new ArrayList(); al.add(3); al.add(2); al.add(1); al.add(4); al.add(5); al.add(6); al.add(6); Iterator iter1 = al.iterator(); while(iter1.hasNext()){ System.out.println(iter1.next()); }
  • 19. Example: ArrayList (Using Generics + Iterating using Iterator and for-each loop) Classification: Restricted Page 20 import java.util.*; class TestCollection1{ public static void main(String args[]){ ArrayList<String> list=new ArrayList<String>();//Creating arraylist list.add("Ravi");//Adding object in arraylist list.add("Vijay"); list.add("Ravi"); list.add("Ajay"); //Traversing list through Iterator Iterator itr=list.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } //Traversing using for-each loop for(String obj:list) System.out.println(obj); }
  • 20. User-defined class objects in Java ArrayList Classification: Restricted Page 21 class Student{ int rollno; String name; int age; Student(int rollno,String name,int age){ this.rollno=rollno; this.name=name ; this.age=age; } } import java.util.*; public class TestCollection3{ public static void main(String args[]){ //Creating user-defined class objects Student s1=new Student(101,"Sonoo",23); Student s2=new Student(102,"Ravi",21); Student s3=new Student(103,"Hanumat",25); //creating arraylist ArrayList<Student> al=new ArrayList<Student>(); al.add(s1);//adding Student class object al.add(s2); al.add(s3); //Getting Iterator Iterator itr=al.iterator(); //traversing elements of ArrayList object while(itr.hasNext()){ Student st=(Student)itr.next(); System.out.println(st.rollno+" "+st.name+" "+st.age); } }