SlideShare a Scribd company logo
Lecture-9
Instructor Name:
Object Oriented Programming
Today’s Lecture
 Arrays in Java
 foreach Loop
 Grouping Objects
 Making use of Library Classes
2
Arrays
What is an Array
 An array is a container object that holds a fixed number of values of a single
type.
 The length of an array is established when the array is created.
 Here is the way to create an array in java
int[] array;
array=new int[10];
or
int array[]={1,2,3,4,5,6,7};
3
Arrays
Printing an Array
class arrayTest{
public static void main(String arg[]){
int a[]={1,2,3,4,5,6,7};
for(int i=0; i<a.length;i++)
System.out.println(a[i]);
}
}
OUTPUT
1
2
3
4
5
6
7
4
Arrays
Sorting Array Using Built-in Functions
import java.util.Arrays;
class sortAttay{
public static void main(String arg[]){
int a[]={11,2,23,4,15,6,17};
for(int i=0; i<a.length;i++)
System.out.println(a[i]);
Arrays.sort(a);
for(int i=0; i<a.length;i++)
System.out.println(a[i]);
}
}
This will sort the array in ascending order.
5
Arrays
Limitations with Arrays
Elements can not be added dynamically.
Elements cannot be removed automatically
Array size must be define at start
6
Collection in Java
Strength of Java
 As we have seen great strength of java is its rich set of predefined classes that
you can reuse rather than “reinventing the Wheel” again and again
 The classes are grouped into packages- named group of related classes and are
collectively referred to as java class library or java application programming
interface(API).
 One of the API is Collection which is used to store the group of related
objects
 A Collection object can store an arbitrary number of other objects.
 Efficient method to store , organize and retrieve the data with out requiring
additional knowledge of how to store it.
 Have the ability to dynamically change the size to accommodate to more
element
 Reduce size when deleting element from collection.
7
Collection in Java
Collection Examples
 Here are some examples of collection that are related to programming context.
 Electronic calendars store event notes about appointments, meetings,
birthdays, and so on. New notes are added as future events are arranged, and
old notes are deleted as details of past events are no longer needed.
 Libraries record details about the books and journals they own. The catalog
changes as new books are bought and old ones are put into storage or
discarded.
 Universities maintain records of students. Each academic year adds new
records to the collection, while the records of those who have left are moved
to an archive collection. Listing subsets of the collection will be common: all
the students taking first-year CS or all the students due to graduate this year,
for instance.
8
ArrayList<T>
What is ArrayList
 The ArrayList is a Java class that is inherited from (or extends)
the AbstractList class. The ArrayList class implements the List interface.
How to Use ArrayList
 In order to use the ArrayList class in your projects, you must import this class
as follows:
import java.util.ArrayList;
Declaring an ArrayList
 After importing the Java ArrayList class, it is time to declare an object of the
ArrayList class. The default way is:
ArrayList array_name = new ArrayList();
 An array “array_name” of the ten size is created. The ArrayList default
constructor creates an array of ten size, by default. 9
ArrayList<T>
Key Points of ArrayList
 A Java ArrayList is a dynamic array, an array that can grow after it is created.
 The standard arrays are not dynamic i.e. once a standard array is created it
cannot grow. These are of fixed size and you cannot add or remove elements
after these are created whereas the ArrayList allows that.
 ArrayList in Java gives fast iteration.
 It also gives fast random access.
 The ArrayList provides more powerful insertion than the standard arrays.
 Search mechanism in ArrayList is better than standard arrays.
 The ArrayList manipulation is slower as a lot of shifting occur.
 Works with non-primitive data types only.
10
ArrayList<T>
Most Common Methods
11
Methods Description
Add Add an element at the end of collection
Clear Remove all element
Contain Return true if element is present otherwise false
Get Return element at specific index
indexOf Return the index of first occurrence
Remove Remove from speicific index
Size Size f arrayList
trimToSize Trim to capacity to current number of elements
ArrayList<T>
ArrayList Example
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String args[]) {
ArrayList<String> al = new ArrayList<String>();
System.out.println("Initial size of al: " + al.size());
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " +
al.size());
System.out.println("Contents of al: " + al);
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " +
al.size());
System.out.println("Contents of al: " + al); } } 12
ArrayList<T>
ArrayList Example – Output
Initial size of al: 0
Size of al after additions: 7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Contents of al: [C, A2, E, B, D]
13
Collection
Generic Vs Non Generic Collection
 Java collection framework was non-generic before JDK 1.5. Since 1.5, it is
generic.
 Java new generic collection allows you to have only one type of object in
collection. Now it is type safe so typecasting is not required at run time.
 Let's see the old non-generic example of creating java collection.
ArrayList al=new ArrayList();
 Let's see the new generic example of creating java collection.
ArrayList<String> al=new ArrayList<String>();
 In generic collection, we specify the type in angular braces. Now ArrayList is
forced to have only specified type of objects in it. If you try to add another
type of object, it gives compile time error. 14
Collection
Diamond Notation
 Files= new ArrayList<String>();
 It is possible for the java compiler to infer the parameterize the type of object
being created from the type of variable being assigned to
 Files= new ArrayList<>();
 Called Diamond Notion
15
foreach Loop
foreach Loop
 A for-each loop is one way to perform a set of actions repeatedly on the items
in a collection, but without having to write out those actions more than once
 We can summarize the Java syntax and actions of a for-each loop in the
following pseudo-code:
for(ElementType element : collection){
loop body
}
 A for-each loop has two parts: a loop header (the first line of the loop
statement) and a loop body following the header. The body contains those
statements that we wish to perform over and over again.
16
foreach Loop
foreach Loop – contains method
public void listMatching(String searchString)
{
for(String alname : al) {
if(alname.contains(searchString)) {
System.out.println(alname);
}
}
}
17
18

More Related Content

What's hot

Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
Shalabh Chaudhary
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
Riccardo Cardin
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & sets
RatnaJava
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List
Hitesh-Java
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
CPD INDIA
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structures
agorolabs
 
Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets
Hitesh-Java
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
kumar gaurav
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection framework
ankitgarg_er
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Edureka!
 
Java collection
Java collectionJava collection
Java collection
Arati Gadgil
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
Prof. Erwin Globio
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
Sony India Software Center
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshan
Zeeshan Khan
 
07 java collection
07 java collection07 java collection
07 java collection
Abhishek Khune
 
collection framework in java
collection framework in javacollection framework in java
collection framework in java
MANOJ KUMAR
 
Java Collections
Java CollectionsJava Collections
Java Collectionsparag
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
Drishti Bhalla
 
Collections generic
Collections genericCollections generic
Collections generic
sandhish
 
Collections Java e Google Collections
Collections Java e Google CollectionsCollections Java e Google Collections
Collections Java e Google Collections
André Faria Gomes
 

What's hot (20)

Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & sets
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structures
 
Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection framework
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
 
Java collection
Java collectionJava collection
Java collection
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshan
 
07 java collection
07 java collection07 java collection
07 java collection
 
collection framework in java
collection framework in javacollection framework in java
collection framework in java
 
Java Collections
Java CollectionsJava Collections
Java Collections
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
 
Collections generic
Collections genericCollections generic
Collections generic
 
Collections Java e Google Collections
Collections Java e Google CollectionsCollections Java e Google Collections
Collections Java e Google Collections
 

Similar to Lecture 9

collection framework.pptx
collection framework.pptxcollection framework.pptx
collection framework.pptx
SoniaKapoor56
 
Java Unit 2 (Part 2)
Java Unit 2 (Part 2)Java Unit 2 (Part 2)
Java Unit 2 (Part 2)
SURBHI SAROHA
 
List interface in collections framework
List interface in collections frameworkList interface in collections framework
List interface in collections framework
Ravi Chythanya
 
Arrays in java.pptx
Arrays in java.pptxArrays in java.pptx
Arrays in java.pptx
Nagaraju Pamarthi
 
STRINGS IN JAVA
STRINGS IN JAVASTRINGS IN JAVA
Collection framework
Collection frameworkCollection framework
Collection framework
BindhuBhargaviTalasi
 
Advanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptxAdvanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptx
eyemitra1
 
ArrayList.docx
ArrayList.docxArrayList.docx
ArrayList.docx
veerendranath12
 
12_-_Collections_Framework
12_-_Collections_Framework12_-_Collections_Framework
12_-_Collections_FrameworkKrishna Sujeer
 
Pi j3.4 data-structures
Pi j3.4 data-structuresPi j3.4 data-structures
Pi j3.4 data-structures
mcollison
 
Collections and generic class
Collections and generic classCollections and generic class
Collections and generic class
ifis
 
Java collections
Java collectionsJava collections
Java collections
Hamid Ghorbani
 
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...
Sagar Verma
 
JAVA(UNIT 4)
JAVA(UNIT 4)JAVA(UNIT 4)
JAVA(UNIT 4)
SURBHI SAROHA
 
Week_2_Lec_6-10_with_watermarking_(1).pdf
Week_2_Lec_6-10_with_watermarking_(1).pdfWeek_2_Lec_6-10_with_watermarking_(1).pdf
Week_2_Lec_6-10_with_watermarking_(1).pdf
PrabhaK22
 
Lecture 4 - Object Interaction and Collections
Lecture 4 - Object Interaction and CollectionsLecture 4 - Object Interaction and Collections
Lecture 4 - Object Interaction and Collections
Syed Afaq Shah MACS CP
 
01-intro_stacks.ppt
01-intro_stacks.ppt01-intro_stacks.ppt
01-intro_stacks.ppt
soniya555961
 
Java Programming Comprehensive Guide.pptx
Java Programming Comprehensive Guide.pptxJava Programming Comprehensive Guide.pptx
Java Programming Comprehensive Guide.pptx
rangariprajwal4554
 
Collections lecture 35 40
Collections lecture 35 40Collections lecture 35 40
Collections lecture 35 40
bhawna sharma
 

Similar to Lecture 9 (20)

collection framework.pptx
collection framework.pptxcollection framework.pptx
collection framework.pptx
 
Java Unit 2 (Part 2)
Java Unit 2 (Part 2)Java Unit 2 (Part 2)
Java Unit 2 (Part 2)
 
List interface in collections framework
List interface in collections frameworkList interface in collections framework
List interface in collections framework
 
Arrays in java.pptx
Arrays in java.pptxArrays in java.pptx
Arrays in java.pptx
 
STRINGS IN JAVA
STRINGS IN JAVASTRINGS IN JAVA
STRINGS IN JAVA
 
Collection framework
Collection frameworkCollection framework
Collection framework
 
Advanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptxAdvanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptx
 
ArrayList.docx
ArrayList.docxArrayList.docx
ArrayList.docx
 
12_-_Collections_Framework
12_-_Collections_Framework12_-_Collections_Framework
12_-_Collections_Framework
 
Collections
CollectionsCollections
Collections
 
Pi j3.4 data-structures
Pi j3.4 data-structuresPi j3.4 data-structures
Pi j3.4 data-structures
 
Collections and generic class
Collections and generic classCollections and generic class
Collections and generic class
 
Java collections
Java collectionsJava collections
Java collections
 
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 4)
JAVA(UNIT 4)JAVA(UNIT 4)
JAVA(UNIT 4)
 
Week_2_Lec_6-10_with_watermarking_(1).pdf
Week_2_Lec_6-10_with_watermarking_(1).pdfWeek_2_Lec_6-10_with_watermarking_(1).pdf
Week_2_Lec_6-10_with_watermarking_(1).pdf
 
Lecture 4 - Object Interaction and Collections
Lecture 4 - Object Interaction and CollectionsLecture 4 - Object Interaction and Collections
Lecture 4 - Object Interaction and Collections
 
01-intro_stacks.ppt
01-intro_stacks.ppt01-intro_stacks.ppt
01-intro_stacks.ppt
 
Java Programming Comprehensive Guide.pptx
Java Programming Comprehensive Guide.pptxJava Programming Comprehensive Guide.pptx
Java Programming Comprehensive Guide.pptx
 
Collections lecture 35 40
Collections lecture 35 40Collections lecture 35 40
Collections lecture 35 40
 

More from talha ijaz

Lecture 23-24.pptx
Lecture 23-24.pptxLecture 23-24.pptx
Lecture 23-24.pptx
talha ijaz
 
Lecture 22
Lecture 22Lecture 22
Lecture 22
talha ijaz
 
Lecture 20-21
Lecture 20-21Lecture 20-21
Lecture 20-21
talha ijaz
 
Lecture 19
Lecture 19Lecture 19
Lecture 19
talha ijaz
 
Lecture 18
Lecture 18Lecture 18
Lecture 18
talha ijaz
 
Lecture 17
Lecture 17Lecture 17
Lecture 17
talha ijaz
 
Lecture 12
Lecture 12Lecture 12
Lecture 12
talha ijaz
 
Lecture 7
Lecture 7Lecture 7
Lecture 7
talha ijaz
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
talha ijaz
 
Visual perception
Visual perceptionVisual perception
Visual perception
talha ijaz
 
Lecture 11
Lecture 11Lecture 11
Lecture 11
talha ijaz
 
Introduction
IntroductionIntroduction
Introduction
talha ijaz
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
talha ijaz
 

More from talha ijaz (16)

Lecture 23-24.pptx
Lecture 23-24.pptxLecture 23-24.pptx
Lecture 23-24.pptx
 
Lecture 22
Lecture 22Lecture 22
Lecture 22
 
Lecture 20-21
Lecture 20-21Lecture 20-21
Lecture 20-21
 
Lecture 19
Lecture 19Lecture 19
Lecture 19
 
Lecture 18
Lecture 18Lecture 18
Lecture 18
 
Lecture 17
Lecture 17Lecture 17
Lecture 17
 
Lecture 12
Lecture 12Lecture 12
Lecture 12
 
Lecture 7
Lecture 7Lecture 7
Lecture 7
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
Visual perception
Visual perceptionVisual perception
Visual perception
 
Lecture 11
Lecture 11Lecture 11
Lecture 11
 
Introduction
IntroductionIntroduction
Introduction
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
Lecture 1
Lecture 1Lecture 1
Lecture 1
 

Recently uploaded

cyberagent_For New Investors_EN_240424.pdf
cyberagent_For New Investors_EN_240424.pdfcyberagent_For New Investors_EN_240424.pdf
cyberagent_For New Investors_EN_240424.pdf
CyberAgent, Inc.
 
Osisko Development - Investor Presentation - June 24
Osisko Development - Investor Presentation - June 24Osisko Development - Investor Presentation - June 24
Osisko Development - Investor Presentation - June 24
Philip Rabenok
 
Corporate Presentation Probe June 2024.pdf
Corporate Presentation Probe June 2024.pdfCorporate Presentation Probe June 2024.pdf
Corporate Presentation Probe June 2024.pdf
Probe Gold
 
Collective Mining | Corporate Presentation - May 2024
Collective Mining | Corporate Presentation - May 2024Collective Mining | Corporate Presentation - May 2024
Collective Mining | Corporate Presentation - May 2024
CollectiveMining1
 
Investor Day 2024 Presentation Sysco 2024
Investor Day 2024 Presentation Sysco 2024Investor Day 2024 Presentation Sysco 2024
Investor Day 2024 Presentation Sysco 2024
Sysco_Investors
 
Collective Mining | Corporate Presentation - May 2024
Collective Mining | Corporate Presentation - May 2024Collective Mining | Corporate Presentation - May 2024
Collective Mining | Corporate Presentation - May 2024
CollectiveMining1
 
New Tax Regime User Guide Flexi Plan Revised (1).pptx
New Tax Regime User Guide Flexi Plan Revised (1).pptxNew Tax Regime User Guide Flexi Plan Revised (1).pptx
New Tax Regime User Guide Flexi Plan Revised (1).pptx
RajkumarRajamanikam
 
Snam 2023-27 Industrial Plan - Financial Presentation
Snam 2023-27 Industrial Plan - Financial PresentationSnam 2023-27 Industrial Plan - Financial Presentation
Snam 2023-27 Industrial Plan - Financial Presentation
Valentina Ottini
 

Recently uploaded (8)

cyberagent_For New Investors_EN_240424.pdf
cyberagent_For New Investors_EN_240424.pdfcyberagent_For New Investors_EN_240424.pdf
cyberagent_For New Investors_EN_240424.pdf
 
Osisko Development - Investor Presentation - June 24
Osisko Development - Investor Presentation - June 24Osisko Development - Investor Presentation - June 24
Osisko Development - Investor Presentation - June 24
 
Corporate Presentation Probe June 2024.pdf
Corporate Presentation Probe June 2024.pdfCorporate Presentation Probe June 2024.pdf
Corporate Presentation Probe June 2024.pdf
 
Collective Mining | Corporate Presentation - May 2024
Collective Mining | Corporate Presentation - May 2024Collective Mining | Corporate Presentation - May 2024
Collective Mining | Corporate Presentation - May 2024
 
Investor Day 2024 Presentation Sysco 2024
Investor Day 2024 Presentation Sysco 2024Investor Day 2024 Presentation Sysco 2024
Investor Day 2024 Presentation Sysco 2024
 
Collective Mining | Corporate Presentation - May 2024
Collective Mining | Corporate Presentation - May 2024Collective Mining | Corporate Presentation - May 2024
Collective Mining | Corporate Presentation - May 2024
 
New Tax Regime User Guide Flexi Plan Revised (1).pptx
New Tax Regime User Guide Flexi Plan Revised (1).pptxNew Tax Regime User Guide Flexi Plan Revised (1).pptx
New Tax Regime User Guide Flexi Plan Revised (1).pptx
 
Snam 2023-27 Industrial Plan - Financial Presentation
Snam 2023-27 Industrial Plan - Financial PresentationSnam 2023-27 Industrial Plan - Financial Presentation
Snam 2023-27 Industrial Plan - Financial Presentation
 

Lecture 9

  • 2. Today’s Lecture  Arrays in Java  foreach Loop  Grouping Objects  Making use of Library Classes 2
  • 3. Arrays What is an Array  An array is a container object that holds a fixed number of values of a single type.  The length of an array is established when the array is created.  Here is the way to create an array in java int[] array; array=new int[10]; or int array[]={1,2,3,4,5,6,7}; 3
  • 4. Arrays Printing an Array class arrayTest{ public static void main(String arg[]){ int a[]={1,2,3,4,5,6,7}; for(int i=0; i<a.length;i++) System.out.println(a[i]); } } OUTPUT 1 2 3 4 5 6 7 4
  • 5. Arrays Sorting Array Using Built-in Functions import java.util.Arrays; class sortAttay{ public static void main(String arg[]){ int a[]={11,2,23,4,15,6,17}; for(int i=0; i<a.length;i++) System.out.println(a[i]); Arrays.sort(a); for(int i=0; i<a.length;i++) System.out.println(a[i]); } } This will sort the array in ascending order. 5
  • 6. Arrays Limitations with Arrays Elements can not be added dynamically. Elements cannot be removed automatically Array size must be define at start 6
  • 7. Collection in Java Strength of Java  As we have seen great strength of java is its rich set of predefined classes that you can reuse rather than “reinventing the Wheel” again and again  The classes are grouped into packages- named group of related classes and are collectively referred to as java class library or java application programming interface(API).  One of the API is Collection which is used to store the group of related objects  A Collection object can store an arbitrary number of other objects.  Efficient method to store , organize and retrieve the data with out requiring additional knowledge of how to store it.  Have the ability to dynamically change the size to accommodate to more element  Reduce size when deleting element from collection. 7
  • 8. Collection in Java Collection Examples  Here are some examples of collection that are related to programming context.  Electronic calendars store event notes about appointments, meetings, birthdays, and so on. New notes are added as future events are arranged, and old notes are deleted as details of past events are no longer needed.  Libraries record details about the books and journals they own. The catalog changes as new books are bought and old ones are put into storage or discarded.  Universities maintain records of students. Each academic year adds new records to the collection, while the records of those who have left are moved to an archive collection. Listing subsets of the collection will be common: all the students taking first-year CS or all the students due to graduate this year, for instance. 8
  • 9. ArrayList<T> What is ArrayList  The ArrayList is a Java class that is inherited from (or extends) the AbstractList class. The ArrayList class implements the List interface. How to Use ArrayList  In order to use the ArrayList class in your projects, you must import this class as follows: import java.util.ArrayList; Declaring an ArrayList  After importing the Java ArrayList class, it is time to declare an object of the ArrayList class. The default way is: ArrayList array_name = new ArrayList();  An array “array_name” of the ten size is created. The ArrayList default constructor creates an array of ten size, by default. 9
  • 10. ArrayList<T> Key Points of ArrayList  A Java ArrayList is a dynamic array, an array that can grow after it is created.  The standard arrays are not dynamic i.e. once a standard array is created it cannot grow. These are of fixed size and you cannot add or remove elements after these are created whereas the ArrayList allows that.  ArrayList in Java gives fast iteration.  It also gives fast random access.  The ArrayList provides more powerful insertion than the standard arrays.  Search mechanism in ArrayList is better than standard arrays.  The ArrayList manipulation is slower as a lot of shifting occur.  Works with non-primitive data types only. 10
  • 11. ArrayList<T> Most Common Methods 11 Methods Description Add Add an element at the end of collection Clear Remove all element Contain Return true if element is present otherwise false Get Return element at specific index indexOf Return the index of first occurrence Remove Remove from speicific index Size Size f arrayList trimToSize Trim to capacity to current number of elements
  • 12. ArrayList<T> ArrayList Example import java.util.ArrayList; public class ArrayListDemo { public static void main(String args[]) { ArrayList<String> al = new ArrayList<String>(); System.out.println("Initial size of al: " + al.size()); al.add("C"); al.add("A"); al.add("E"); al.add("B"); al.add("D"); al.add("F"); al.add(1, "A2"); System.out.println("Size of al after additions: " + al.size()); System.out.println("Contents of al: " + al); al.remove("F"); al.remove(2); System.out.println("Size of al after deletions: " + al.size()); System.out.println("Contents of al: " + al); } } 12
  • 13. ArrayList<T> ArrayList Example – Output Initial size of al: 0 Size of al after additions: 7 Contents of al: [C, A2, A, E, B, D, F] Size of al after deletions: 5 Contents of al: [C, A2, E, B, D] 13
  • 14. Collection Generic Vs Non Generic Collection  Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic.  Java new generic collection allows you to have only one type of object in collection. Now it is type safe so typecasting is not required at run time.  Let's see the old non-generic example of creating java collection. ArrayList al=new ArrayList();  Let's see the new generic example of creating java collection. ArrayList<String> al=new ArrayList<String>();  In generic collection, we specify the type in angular braces. Now ArrayList is forced to have only specified type of objects in it. If you try to add another type of object, it gives compile time error. 14
  • 15. Collection Diamond Notation  Files= new ArrayList<String>();  It is possible for the java compiler to infer the parameterize the type of object being created from the type of variable being assigned to  Files= new ArrayList<>();  Called Diamond Notion 15
  • 16. foreach Loop foreach Loop  A for-each loop is one way to perform a set of actions repeatedly on the items in a collection, but without having to write out those actions more than once  We can summarize the Java syntax and actions of a for-each loop in the following pseudo-code: for(ElementType element : collection){ loop body }  A for-each loop has two parts: a loop header (the first line of the loop statement) and a loop body following the header. The body contains those statements that we wish to perform over and over again. 16
  • 17. foreach Loop foreach Loop – contains method public void listMatching(String searchString) { for(String alname : al) { if(alname.contains(searchString)) { System.out.println(alname); } } } 17
  • 18. 18