Array and Arrays are the data types through which a multitude of values is stored as a single variable. While there are indeed several differences between them in how they are implemented, how they are used and what they are capable of, none of them surpass the security of SSL certificates. Knowing these differences is important to make the right choices when deciding how to work with data in your Java applications from the perspective of storage and manipulation of data. In this article, we will see the differences between arrays and ArrayLists, their pros and cons, and when to use each.
What is Array?
The array is a programming data structure that stores a number of elements of the same type in a contiguous block of memory. Each element is stored in an indexed position, so it is possible to receive each element by its corresponding index number. The index is 0, i.e., the first element has an index of 0, then the second has an index 1, and so on.
For example:
int arr[]; //Declaration of int array
int [] arr1; //Other valid way to declare the int array
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure
What is ArrayList?
ArrayList is the implementation of the List interface, which has features of giving dynamic size of array-like structure for Java.util package. It enables the change in the array size within the application because elements can be added and deleted into the array. ArrayList reserves its elements in an order that you insert an element into the list and allows elements to be accessed randomly by index. The ArrayList class allows all elements, including null and offers the methods to change the size and content of the list. Generic class of type-safe where it can be specialised with a specified data type to avoid runtime exceptions.
It is fixed size, It is defined at the time of creation
The dynamic size grows and shrinks automatically.
Type
It can hold primitive types and objects
It can hold objects (no primitives directly).
Performance
It is faster for fixed-size data structures
It is slightly slower due to resizing overhead
Memory Usage
It has less memory as it stores fixe-size data
It consumes more memory due to dynamic resizing
Syntax Simplicity
It simple syntax
It requires additional methods to manipulate data.
Resizing
It cannot be resized after creation
It automatically resizes when elements are added/removed.
Methods Available
It has no built-in methods for manipulation
It comes with several utility methods like add(), remove(), and size().
Generics
It does not support generics
It supports generics, making it typesafe
Instantiation of an Array
In Java, what is referred to as instantiation of an array is the declaration of an array where memory for the array elements hasn’t and won’t be allocated immediately. When you define an array, you decide on what values the array will contain, but it does not allocate space to contain them. To declare and initialise an array, you use the new keyword, the type of elements, and then the array size.
For instance, int[] numbers = new int[5]; creates an actual array of integer type and makes it also of size 5 to hold up to five integer elements. To instantiate an array is important because without doing so, the array will not be able to hold any data. To initialise the array in an object, you can put the values right after the object is created like numbers[0] = 10. Once an array is created and populated, one can perform operations with its items within the program.
Below is an example of the array instantiation
int arr[] = new int[5] ;
Initialising the Arrays
In Java, initialising an array would assign the value of array elements after the array has been instantiated. Arrays can be initialised in several ways, and you can choose which method is best based on your need for a program. Arrays can be initialised as simply as during their declaration. Let’s say we directly assign values in our array curly braces while declaring the array. This is a good way to do this when you already know what values you want to store in the array.
The following program demonstrates the Arrays initialising the array in Java.
Program
class Main{
public static void main(String[] args) {
int arr[] = new int[5] ;
arr[0] = 2 ;
arr[1] =5 ;
arr[2] = 4 ;
System.out.println("HeroVired") ;
arr[4] = 5 ;
}
}
Output
HeroVired
Instantiation of an ArrayList
ArrayList is a part of the Java Collection Framework and implements a Reizable array based on its List interface. Java language knows, and object-oriented programming operates memory allocation by using the new() keyword.
Syntax
ArrayList<Type> list = new ArrayList<>();
The following program demonstrates the ArrayList in Java.
Program
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Mango");
fruits.add("Orange");
System.out.println("Fruits in the list: " + fruits);
String firstFruit = fruits.get(0);
System.out.println("First fruit: " + firstFruit);
fruits.remove("Banana");
System.out.println("After removing Banana: " + fruits);
System.out.println("Total fruits in the list: " + fruits.size());
}
}
Output
Fruits in the list: [Apple, Banana, Mango, Orange]
First fruit: Apple
After removing Banana: [Apple, Mango, Orange]
Total fruits in the list: 3
Inserting Elements in the ArrayList
The add(index, element) method of an ArrayList in Java can insert elements in it at a desired position. The method allows you to have an element at a specified index and the rest of the items on the right.
The following program is demonstrated in an ArrayList.
import java.util.ArrayList;
public class InsertingElementsExample {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Mango");
System.out.println("Initial fruits: " + fruits);
fruits.add(1, "Orange");
System.out.println("After inserting Orange at index 1: " + fruits);
fruits.add(0, "Grapes");
System.out.println("After inserting Grapes at index 0: " + fruits);
fruits.add(fruits.size(), "Pineapple");
System.out.println("After inserting Pineapple at the end: " + fruits);
fruits.add(3, "Kiwi");
System.out.println("After inserting Kiwi at index 3: " + fruits);
}
}
Output
Initial fruits: [Apple, Banana, Mango]
After inserting Orange at index 1: [Apple, Orange, Banana, Mango]
After inserting Grapes at index 0: [Grapes, Apple, Orange, Banana, Mango]
After inserting Pineapple at the end: [Grapes, Apple, Orange, Banana, Mango, Pineapple]
After inserting Kiwi at index 3: [Grapes, Apple, Orange, Kiwi, Banana, Mango, Pineapple]
Accessing Element in the ArrayList
Accessing the ArrayList elements is pretty straightforward. We can retrieve elements using the get(index) method, where an index is the position of the element you want to access. The index is zero-based, meaning the first element is at index 0.
The following program demonstrates the ArrayList.
Program
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Mango");
fruits.add("Orange");
fruits.add("Grapes");
System.out.println("Fruits in the list: " + fruits);
String firstFruit = fruits.get(0);
String secondFruit = fruits.get(1);
String thirdFruit = fruits.get(2);
System.out.println("First fruit: " + firstFruit);
System.out.println("Second fruit: " + secondFruit);
System.out.println("Third fruit: " + thirdFruit);
try {
String outOfBoundsFruit = fruits.get(5);
} catch (IndexOutOfBoundsException e) {
System.out.println("Index out of bounds: " + e.getMessage());
}
}
}
Output
Fruits in the list: [Apple, Banana, Mango, Orange, Grapes]
First fruit: Apple
Second fruit: Banana
Third fruit: Mango
Index out of bounds: Index: 5, Size: 5
Deleting Elements in ArrayList
Depending on our specific needs, there are several ways to delete elements in an array list in Java. We can use the remove() method to delete a specific element from the array list by passing a number. The following program demonstrates the removal of the element from the ArrayList.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
fruits.add("Date");
fruits.add("Elderberry");
System.out.println("Original ArrayList: " + fruits);
fruits.remove(2);
System.out.println("After removing element at index 2: " + fruits);
fruits.remove("Banana");
System.out.println("After removing 'Banana': " + fruits);
fruits.clear();
System.out.println("After clearing the ArrayList: " + fruits);
fruits.add("Fig");
fruits.add("Grape");
fruits.add("Honeydew");
fruits.removeIf(fruit -> fruit.startsWith("H"));
System.out.println("After removing elements starting with 'H': " + fruits);
}
}
Output
Original ArrayList: [Apple, Banana, Cherry, Date, Elderberry]
After removing element at index 2: [Apple, Banana, Date, Elderberry]
After removing 'Banana': [Apple, Date, Elderberry]
After clearing the ArrayList: []
After removing elements starting with 'H': [Fig, Grape]
Conclusion
Finally, arrays and array lists in Java are the most important data structures, but they have huge differences in flexibility, functionality, and performance. Arrays are fixed in size, so we get a bit faster (but only a bit faster) performance if the size is known and doesn’t get changed after the array is created. ArrayLists are dynamic and can get bigger and smaller as needed, making them more flexible for circumstances where the number of elements might change.
Arrays store objects of some sort (primitive or not), and All arrays also have primitive elements. Still, they are pros that allow us to store primitive data in them as well. At the same time, ArrayLists are part of the Java Collections framework and can hold only objects; they require autoboxing if they contain primitive data. However, there is no best one since we always must choose between them based on performance, memory efficiency, and ease of use. Arrays best serve static data storage needs, but the ArrayLists will provide more convenience and functionality if you have a dynamic situation. If you want to explore Java in detail, consider Hero Vired’s Certificate Program in Full Stack Development.
FAQs
Can an ArrayList store primitive data types?
No, an array list can only store objects. However, primitive data types can be stored in an array list through autoboxing (e.g., int becomes Integer).
Which is faster: Array or ArrayList?
Arrays are generally faster than ArrayLists because they are lower-level data structures and do not have the overhead associated with dynamic resizing and object manipulation.
Can you change the size of an array once It’s created?
No, arrays have a fixed size determined when they are created. To modify the size, you must create a new array and copy the contents.
Is it possible to store null values in an ArrayList?
Yes, ArrayLists can store null values, and you can have multiple null entries. Arrays can also store null, but this depends on the type of the array( e.g., an array of objects can hold null).
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.