The ArrayList
class in Java is a widely used data structure for storing dynamic data. It implements the List
interface, a part of Java's Collection
framework. The developers favor ArrayList
over the normal array because of its flexibility to dynamically grow and shrink.
ArrayList
vs. Array
There are five notable differences between an ArrayList
and an array in Java:
- Unlike an array that has a fixed length,
ArrayList
is resizable. When a new element is added, it is extended automatically. Likewise, when an element is removed, it shrinks. There are no empty slots. ArrayList
uses an array internally to store the elements. So you can use the zero-based index to randomly retrieve the elements.- Just like the array, you can store duplicate and null values in
ArrayList
. ArrayList
maintains the insertion order of the elements.- Unlike the array that can be of primitive type, you cannot use primitives like
int
,double
, andchar
to create anArrayList
. You must use reference types likeString
,Integer
, orDouble
to create anArrayList
.
Creating an ArrayList
There are multiple ways to create an ArrayList
:
// create an empty array list
List<String> list = new ArrayList<>();
// create and initialize array list
List<String> list2 = new ArrayList<>(Arrays.asList("🐭", "🐧", "🦅", "🐦"));
// create an array list with a specified initial size
List<String> list3 = new ArrayList<>(10);
// Java 8 `Arrays.asList()` method (immutable)
List<Integer> list4 = Arrays.asList(1, 2, 3, 4, 5);
// Java 9 `List.of()` method (immutable)
List<Integer> list5 = List.of(1, 2, 3, 4, 5);
ArrayList
Methods
The ArrayList
class also inherits methods from parent classes List
, Collection
, and Iterable
. The most popular methods are set()
, get()
, size()
, remove()
, and isEmpty()
. Here is a simple example of an ArrayList
showing the use of these methods:
List<String> list = new ArrayList<>();
// add elments
list.add("🐭");
list.add("🐧");
list.add("🦅");
list.add("🐦");
// get items
list.get(0); // 🐭
list.get(2); // 🦅
// get elements count
list.size(); // 4
// update element at index 1
list.set(1, "🦄");
list.get(1); // 🦄
// remove elements using value
list.remove("🦄"); // true
// remove elements using the index
list.remove(0); // true
// check if list is empty
list.isEmpty(); // false
Iterating over ArrayList
You can iterate over the ArrayList
elements through multiple methods:
// simple `for` loop
for (int i = 0; i < foods.size(); i++) {
System.out.println(foods.get(i));
}
// for each loop
for (String item : foods) {
System.out.println(item);
}
// Java 8 `forEach` from Streams API
foods.forEach(System.out::println);
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.