In Java SE 22, the main difference between an array and an ArrayList lies in their nature and features:
1. Type:
– Array: Arrays in Java are fixed-size data structures that store elements of the same type in contiguous memory locations.
– ArrayList: ArrayList is a part of the Java Collections Framework and is a dynamic array-like data structure that can resize itself dynamically. It can hold elements of any type.
2. Size:
– Array: The size of an array is fixed when it’s created and cannot be changed.
– ArrayList: The size of an ArrayList can dynamically grow or shrink as elements are added or removed.
3. Mutability:
– Array: Once an array is created, its size and elements cannot be changed. You cannot add or remove elements from a fixed-size array.
– ArrayList: ArrayLists are mutable, meaning you can add, remove, or replace elements freely.
4. Methods:
– Array: Arrays support a limited set of methods such as accessing elements by index, copying arrays, and getting the length of the array.
– ArrayList: ArrayList provides a wide range of methods for manipulation such as adding elements, removing elements, checking if an element exists, getting the size, and more. It also inherits methods from the List interface.
5. Performance:
– Array: Arrays generally offer better performance for direct element access, as they directly access memory locations based on index.
– ArrayList: ArrayLists might have slightly lower performance for direct access due to the overhead of dynamic resizing and the use of wrapper objects for primitive types.
Here’s a basic example to illustrate the difference:
// Array example int[] arr = new int[5]; // Creating an array of size 5 arr[0] = 10; // Assigning value to the first element // ArrayList example import java.util.ArrayList; ArrayList<Integer> arrayList = new ArrayList<>(); arrayList.add(10); // Adding element to ArrayList
In summary, arrays are suitable for situations where the size is known beforehand and doesn’t change, while ArrayLists are more flexible and suitable for situations where the size might change dynamically.