Java Arraylist in Java
ArrayList in Java
An ArrayList is a part of the Java Collections Framework and is a resizable array that implements the List interface. Unlike arrays, ArrayLists can grow dynamically when elements are added, and they also provide many methods for manipulating the data.
Key Features:
Dynamic Sizing: It automatically resizes when elements are added or removed.
Indexed Access: You can access elements by index.
Duplicates Allowed: You can add duplicate elements.
Null Elements Allowed: It supports
nullelements.Ordered: It maintains the insertion order.
Creating an ArrayList
import java.util.ArrayList;public class ArrayListExample { public static void main(String[] args) { // Creating an ArrayList of Integer type ArrayList<Integer> numbers = new ArrayList<>(); // Adding elements to the ArrayList numbers.add(10); // Adds 10 to the list numbers.add(20); // Adds 20 to the list numbers.add(30); // Adds 30 to the list // Display the ArrayList System.out.println("ArrayList: " + numbers); }}Output:
ArrayList: [10, 20, 30]Commonly Used Methods in ArrayList
Adding Elements:
add(E e): Adds the element to the end of the list.add(int index, E element): Inserts the element at the specified index.
numbers.add(40); // Adds 40 at the endnumbers.add(1, 15); // Adds 15 at index 1Accessing Elements:
get(int index): Returns the element at the specified index.
int firstElement = numbers.get(0); // Gets the first element (index 0)System.out.println(firstElement); // Output: 10Removing Elements:
remove(int index): Removes the element at the specified index.remove(Object o): Removes the first occurrence of the specified element.
numbers.remove(1); // Removes element at index 1numbers.remove(Integer.valueOf(30)); // Removes element with value 30Size of ArrayList:
size(): Returns the number of elements in the ArrayList.
int size = numbers.size(); // Gets the size of the listSystem.out.println("Size: " + size); // Output: Size: 3Checking if the ArrayList Contains an Element:
contains(Object o): Checks if the list contains the specified element.
boolean contains = numbers.contains(10); // Checks if 10 is in the listSystem.out.println("Contains 10: " + contains); // Output: trueClearing All Elements:
clear(): Removes all elements from the ArrayList.
numbers.clear(); // Clears all elementsSystem.out.println("ArrayList after clear: " + numbers); // Output: []Checking if ArrayList is Empty:
isEmpty(): Returnstrueif the list is empty.
boolean isEmpty = numbers.isEmpty(); // Checks if the list is emptySystem.out.println("Is list empty: " + isEmpty); // Output: true
Example: Using ArrayList with Different Data Types
import java.util.ArrayList;public class MixedDataTypesArrayList { public static void main(String[] args) { // ArrayList of Strings ArrayList<String> fruits = new ArrayList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); // ArrayList of Integers ArrayList<Integer> numbers = new ArrayList<>(); numbers.add(100); numbers.add(200); numbers.add(300); // Displaying ArrayLists System.out.println("Fruits: " + fruits); System.out.println("Numbers: " + numbers); }}Output:
Fruits: [Apple, Banana, Cherry]Numbers: [100, 200, 300]Example: Iterating Over an ArrayList
You can use different ways to iterate over an ArrayList:
Using a for-each loop:
for (String fruit : fruits) { System.out.println(fruit);}Using a traditional for loop:
for (int i = 0; i < fruits.size(); i++) { System.out.println(fruits.get(i));}Using an Iterator:
Iterator<String> iterator = fruits.iterator();while (iterator.hasNext()) { System.out.println(iterator.next());}Using Streams (Java 8+):
fruits.forEach(fruit -> System.out.println(fruit));
Example: Sorting an ArrayList
You can sort an ArrayList using Collections.sort() or streams.
Using Collections.sort():
import java.util.*;ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(5, 1, 3, 4, 2));Collections.sort(numbers);System.out.println(numbers); // Output: [1, 2, 3, 4, 5]Using Streams:
List<Integer> sortedList = numbers.stream().sorted().collect(Collectors.toList());System.out.println(sortedList); // Output: [1, 2, 3, 4, 5]
Key Methods Summary:
| Method | Description |
|---|---|
add(E e) | Adds an element to the end of the list |
get(int index) | Retrieves the element at the specified index |
remove(int index) | Removes the element at the specified index |
remove(Object o) | Removes the first occurrence of the specified element |
size() | Returns the number of elements in the list |
contains(Object o) | Checks if the list contains the specified element |
clear() | Removes all elements from the list |
isEmpty() | Checks if the list is empty |
Conclusion
ArrayLists are dynamic and flexible, making them ideal when you need a resizable collection.
They support various methods to manage data (add, remove, check for elements, etc.).
You can easily sort, iterate, and manipulate ArrayLists in various ways.
Would you like to explore ArrayLists with custom objects or performance considerations when using ArrayLists? Let me know! ?