Lecture - 12-Java ArrayList
Lecture - 12-Java ArrayList
ArrayList in Java
Afsara Tasneem Misha
Lecturer
Department of CSE
Daffodil International University
Today’s Contents
Java ArrayList
• ArrayList
ArrayList<Type> ArrayListName = new ArrayList<Type>();
Ex.
ArrayList<Integer> arrL1 = new ArrayList<>();
ArrayList<String> arrL2 = new ArrayList<>();
ArrayList<Object> arrL3 = new ArrayList<>();
Differences between Array and ArrayList
• An array is basic functionality provided by Java. ArrayList is part of collection
framework in Java.
• Therefore array members are accessed using [], while ArrayList has a set of
methods to access elements and modify them.
• Array is a fixed size data structure while ArrayList is Dynamic. One need not to
mention the size of Arraylist while creating its object.
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
System.out.println(cars);
}
}
Built-in Methods for ArrayList
• To add elements to the ArrayListuse use the add() method cars.add("Volvo");
• cars.add("BMW");
• To access an element in the ArrayList, use the get() method and refer to the index number:
• cars.get(0);
• To modify/change an element, use the set() method and refer to the index number:
• cars.set(0, “Alien");
• To remove an element, use the remove() method and refer to the index number:
• cars.remove(0);
• To remove all the elements in the ArrayList, use the clear() method:
• cars.clear();
• To find out how many elements an ArrayList have, use the size method:
• cars.size();
Loop Through an ArrayList
public class MyClass {
Output:
public static void main(String[] args) {
Volvo
ArrayList<String> cars = new ArrayList<String>(); BMW
Ford
cars.add("Volvo"); Mazda
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
}
}
Sort an ArrayList
import java.util.ArrayList;
import java.util.Collections; // Import the Collections class Output:
BMW
public class MyClass {
Ford
public static void main(String[] args) {
Mazda
ArrayList<String> cars = new ArrayList<String>(); Volvo
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
1. Create an Array List of Integer Data type, Show All the Basic Person
Functions (Add, get, set, remove, clear size)
- name: String
- age: int
2. Consider the Following UML. Now Convert the UML into JAVA
code.
▪ Create ArrayList of Persons.
+Person(String, int)
▪ Add Information of them
+display(): void
▪ Display their Information from ArrayList
+main(String[] ) : void
Thank You