A big limitation of static arrays in Java is the fact that once the array is created, it has a fixed size.
The ArrayList overcomes this limitation by having variable size and allowing for elements to be added or removed.
Creation:
We create an ArrayList by using the keywords new and ArrayList, then writing the type of the elements inside <> followed by paranthesis:
new ArrayList<String>();
This code creates an empty ArrayList where each item is a String.
Casting:
A good practice is to cast the created ArrayList in its interface by using a List variable and specifying there the type of the elements, like this:
List<String> sandwich = new ArrayList<>();
Initialization:
You can also initialize an ArrayList at creation by using the List.of() function and put a comma between each entry, like this:
List<String> sandwich = new ArrayList<>(
List.of("peanut butter", "jelly", "bread")
);
We created an ArrayList named sandwich which consits of 3 items: "peanut butter", "jelly" and "bread".
Assignment
Follow the Coding Tutorial and let's create some ArrayLists!
Hint
Look at the examples above if you get stuck.
In this lesson, we will explore the ArrayList class in Java, a part of the Java Collections Framework. The ArrayList is a resizable array, which can grow as needed to accommodate new elements. This flexibility makes it a powerful tool for managing collections of data where the size may change dynamically.
Understanding how to use ArrayList is crucial for any Java programmer, as it is commonly used in various applications, from simple programs to complex enterprise-level systems.
The ArrayList class is part of the java.util package and implements the List interface. Unlike arrays, which have a fixed size, an ArrayList can dynamically resize itself when elements are added or removed.
Here is a simple example to illustrate the basic usage of ArrayList:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
// Creating an ArrayList of Strings
List<String> fruits = new ArrayList<>();
// Adding elements to the ArrayList
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
// Printing the ArrayList
System.out.println(fruits);
}
}
In this example, we create an ArrayList of String type, add three elements to it, and print the list.
Let's delve deeper into some key concepts and techniques related to ArrayList:
add() method to add elements to the ArrayList.get() method to access elements at a specific index.remove() method to remove elements from the ArrayList.size() method to get the number of elements in the ArrayList.Here is an example demonstrating these concepts:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
// Accessing elements
System.out.println("First fruit: " + fruits.get(0));
// Removing an element
fruits.remove("Banana");
// Size of the list
System.out.println("Number of fruits: " + fruits.size());
}
}
Let's look at some practical examples and use cases for ArrayList:
import java.util.ArrayList;
import java.util.List;
public class ToDoList {
public static void main(String[] args) {
List<String> tasks = new ArrayList<>();
tasks.add("Buy groceries");
tasks.add("Clean the house");
tasks.add("Pay bills");
System.out.println("To-Do List: " + tasks);
// Marking a task as done
tasks.remove("Clean the house");
System.out.println("Updated To-Do List: " + tasks);
}
}
import java.util.ArrayList;
import java.util.List;
public class StudentNames {
public static void main(String[] args) {
List<String> students = new ArrayList<>();
students.add("John");
students.add("Jane");
students.add("Jack");
System.out.println("Student Names: " + students);
// Adding a new student
students.add("Jill");
System.out.println("Updated Student Names: " + students);
}
}
When working with ArrayList, there are some common pitfalls to avoid and best practices to follow:
ArrayList while iterating over it. Use an Iterator to safely remove elements.ArrayList to avoid ClassCastException.For more advanced usage, you can explore the following techniques:
Collections.sort() to sort the elements in an ArrayList.Collections.synchronizedList() to create a synchronized ArrayList for thread-safe operations.Here is an example of sorting an ArrayList:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SortArrayList {
public static void main(String[] args) {
List<String> fruits = new ArrayList<>();
fruits.add("Banana");
fruits.add("Apple");
fruits.add("Cherry");
// Sorting the ArrayList
Collections.sort(fruits);
System.out.println("Sorted Fruits: " + fruits);
}
}
Here is a comprehensive example that demonstrates the correct use of ArrayList:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ArrayListExample {
public static void main(String[] args) {
// Creating an ArrayList of Strings
List<String> fruits = new ArrayList<>();
// Adding elements to the ArrayList
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
// Accessing elements
System.out.println("First fruit: " + fruits.get(0));
// Removing an element
fruits.remove("Banana");
// Size of the list
System.out.println("Number of fruits: " + fruits.size());
// Sorting the ArrayList
Collections.sort(fruits);
System.out.println("Sorted Fruits: " + fruits);
}
}
When debugging and testing code involving ArrayList, consider the following tips:
ArrayList at various stages.ArrayList.Here is an example of a simple unit test for an ArrayList:
import org.junit.Test;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
public class ArrayListTest {
@Test
public void testAddElement() {
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
assertEquals(1, fruits.size());
assertEquals("Apple", fruits.get(0));
}
}
When working with ArrayList, consider the following strategies:
ArrayList.ArrayList to improve your skills.In this lesson, we covered the basics and advanced concepts of ArrayList in Java. We explored how to create, manipulate, and optimize ArrayList for various use cases. Mastering ArrayList is essential for efficient data management in Java applications.
Keep practicing and exploring further applications of ArrayList to enhance your programming skills.
For further reading and practice, consider the following resources:
Our interactive tutorials and AI-assisted learning will help you master problem-solving skills and teach you the algorithms to know for coding interviews.
Start Coding for FREE