An ArrayList in Java is a dynamic data structure that allows you to store and manipulate a collection of elements. It’s part of the java.util package and provides flexibility in handling groups of objects.
import java.util.ArrayList;
// Syntax for creating an ArrayList
ArrayList<Type> listName = new ArrayList<>();
Code language: JavaScript (javascript)
Methods:
Adding Elements
- add(element): Appends an element to the end of the list.
- add(index, element): Inserts an element at a specified index.
Accessing Elements
- get(index): Retrieves the element at the specified index.
Removing Elements
- remove(index): Removes the element at the specified index.
- remove(element): Removes the first occurrence of the specified element.
Size and Capacity
- size(): Returns the number of elements in the list.
- isEmpty(): Checks if the list is empty.
Other Operations
- contains(element): Checks if the list contains a specific element.
- clear(): Removes all elements from the list.
- toArray(): Converts the list to an array.
import java.util.ArrayList;
public class StudentListExample {
public static void main(String[] args) {
// Creating an ArrayList to store student names
ArrayList<String> students = new ArrayList<>();
// Adding students to the ArrayList
students.add("Paani");
students.add("Mahesh");
students.add("Datta");
students.add("Ganesh");
students.add("Harsha");
// Displaying the names of students
System.out.println("List of students:");
for (String student : students) {
System.out.println(student);
}
// Adding a new student at index 2
students.add(2, "NewStudent");
// Displaying the updated list
System.out.println("\nUpdated list of students:");
for (String student : students) {
System.out.println(student);
}
// Removing a different student (Datta)
students.remove("Datta");
// Displaying the final list
System.out.println("\nFinal list of students:");
for (String student : students) {
System.out.println(student);
}
}
}D:\>javac HashtableExample.java
D:\>java HashtableExample
Hashtable of students:
{Ganesh=104, Paani=101, Mahesh=102, Harsha=105, Datta=103}
Removed student 'Datta' with roll number: 103
Updated Hashtable of students:
{Ganesh=104, Paani=101, Mahesh=102, Harsha=105}
Does the Hashtable contain student 'Harsha'? true
Iterating over Hashtable entries using enumeration:
Student: Ganesh, Roll Number: 104
Student: Paani, Roll Number: 101
Student: Mahesh, Roll Number: 102
Student: Harsha, Roll Number: 105
Size of the Hashtable: 4
Is the Hashtable empty now? trueCode language: JavaScript (javascript)