Introduction to ArrayList
An ArrayList in Java is a part of the Java Collections Framework and is a resizable array implementation of the List interface. Unlike arrays, ArrayList can dynamically grow and shrink in size. It provides more flexibility in terms of adding, removing, and accessing elements.
Key Features of ArrayList
- Dynamic Size: Automatically resizes itself when elements are added or removed.
- Indexed Access: Allows fast random access to elements using an index.
- Non-Synchronized: Not thread-safe by default, but can be synchronized externally.
- Allows Duplicates: Can store duplicate elements.
- Maintains Insertion Order: Elements are stored in the order they are inserted.
Creating an ArrayList
To use ArrayList, you need to import it from the java.util package.
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
// Creating an ArrayList of Strings
ArrayList<String> fruits = new ArrayList<>();
// Adding elements to the ArrayList
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
// Printing the ArrayList
System.out.println(fruits);
}
}Explanation
- Import Statement:
import java.util.ArrayList;imports theArrayListclass. - Creating an ArrayList:
ArrayList<String> fruits = new ArrayList<>();creates anArrayListto storeStringelements. - Adding Elements:
fruits.add("Apple");adds elements to theArrayList. - Printing the ArrayList:
System.out.println(fruits);prints the elements of theArrayList.
Common Methods of ArrayList
Here are some commonly used methods of the ArrayList class:
| Method | Description |
|---|---|
add(E e) |
Appends the specified element to the end of the list. |
add(int index, E element) |
Inserts the specified element at the specified position in the list. |
get(int index) |
Returns the element at the specified position in the list. |
set(int index, E element) |
Replaces the element at the specified position in the list with the specified element. |
remove(int index) |
Removes the element at the specified position in the list. |
size() |
Returns the number of elements in the list. |
clear() |
Removes all elements from the list. |
isEmpty() |
Returns true if the list contains no elements. |
contains(Object o) |
Returns true if the list contains the specified element. |
Practical Examples
Example 1: Basic Operations
import java.util.ArrayList;
public class ArrayListOperations {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();
// Adding elements
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
// Accessing elements
System.out.println("First fruit: " + fruits.get(0));
// Modifying elements
fruits.set(1, "Mango");
System.out.println("Modified list: " + fruits);
// Removing elements
fruits.remove(2);
System.out.println("After removal: " + fruits);
// Checking size
System.out.println("Size of the list: " + fruits.size());
// Checking if list contains an element
System.out.println("Contains 'Apple': " + fruits.contains("Apple"));
// Clearing the list
fruits.clear();
System.out.println("List after clearing: " + fruits.isEmpty());
}
}Explanation
- Adding Elements: Adds "Apple", "Banana", and "Orange" to the
ArrayList. - Accessing Elements: Retrieves the first element using
get(0). - Modifying Elements: Changes the second element to "Mango" using
set(1, "Mango"). - Removing Elements: Removes the third element using
remove(2). - Checking Size: Prints the size of the
ArrayListusingsize(). - Checking Containment: Checks if "Apple" is in the list using
contains("Apple"). - Clearing the List: Clears all elements using
clear()and checks if the list is empty usingisEmpty().
Practical Exercises
Exercise 1: Basic ArrayList Operations
Task: Create an ArrayList of integers, add five integers to it, and perform the following operations:
- Print the
ArrayList. - Retrieve and print the third element.
- Change the second element to a new value.
- Remove the fourth element.
- Print the final
ArrayList.
Solution:
import java.util.ArrayList;
public class ArrayListExercise {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
// Adding elements
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
numbers.add(50);
// Printing the ArrayList
System.out.println("Original list: " + numbers);
// Retrieving and printing the third element
System.out.println("Third element: " + numbers.get(2));
// Changing the second element
numbers.set(1, 25);
System.out.println("After modification: " + numbers);
// Removing the fourth element
numbers.remove(3);
System.out.println("After removal: " + numbers);
}
}Exercise 2: ArrayList of Custom Objects
Task: Create a class Student with fields id and name. Create an ArrayList of Student objects, add three students to it, and perform the following operations:
- Print the
ArrayList. - Retrieve and print the name of the student with the second
id. - Change the name of the student with the first
id. - Remove the student with the third
id. - Print the final
ArrayList.
Solution:
import java.util.ArrayList;
class Student {
int id;
String name;
Student(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Student{id=" + id + ", name='" + name + "'}";
}
}
public class StudentArrayList {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
// Adding students
students.add(new Student(1, "Alice"));
students.add(new Student(2, "Bob"));
students.add(new Student(3, "Charlie"));
// Printing the ArrayList
System.out.println("Original list: " + students);
// Retrieving and printing the name of the student with the second id
System.out.println("Student with second id: " + students.get(1).name);
// Changing the name of the student with the first id
students.get(0).name = "Alicia";
System.out.println("After modification: " + students);
// Removing the student with the third id
students.remove(2);
System.out.println("After removal: " + students);
}
}Conclusion
In this section, we covered the basics of ArrayList in Java, including its key features, common methods, and practical examples. We also provided exercises to help reinforce the concepts. Understanding ArrayList is crucial for working with dynamic collections of data in Java, and it serves as a foundation for more advanced data structures and algorithms. In the next section, we will explore LinkedList, another important data structure in the Java Collections Framework.
Java Programming Course
Module 1: Introduction to Java
- Introduction to Java
- Setting Up the Development Environment
- Basic Syntax and Structure
- Variables and Data Types
- Operators
Module 2: Control Flow
Module 3: Object-Oriented Programming
- Introduction to OOP
- Classes and Objects
- Methods
- Constructors
- Inheritance
- Polymorphism
- Encapsulation
- Abstraction
Module 4: Advanced Object-Oriented Programming
Module 5: Data Structures and Collections
Module 6: Exception Handling
Module 7: File I/O
Module 8: Multithreading and Concurrency
- Introduction to Multithreading
- Creating Threads
- Thread Lifecycle
- Synchronization
- Concurrency Utilities
Module 9: Networking
- Introduction to Networking
- Sockets
- ServerSocket
- DatagramSocket and DatagramPacket
- URL and HttpURLConnection
