Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
In Java, arrays & ArrayLists are two basic ways to store collections of data. An array is a fixed-size data structure that holds items of the same type, like a row of boxes. An ArrayList is more flexible - it's a resizable array that can grow or shrink as needed.
In this article, we'll discuss the key differences between arrays & ArrayLists in Java. We'll check out how to create & use them with code examples. This article will clear all your doubts regarding Array vs ArrayList in Java
Methods of Creating Arrays
In Java, you can create arrays in a couple different ways:
Simple fixed-sized arrays
Dynamically sized arrays
Simple fixed-sized arrays are the most basic. You decide the size of the array when you create it, and that size stays the same. Here's how to declare a simple integer array of size 5:
int[] numbers = new int[5];
This creates an array called "numbers" that can hold 5 integers. You can access each slot using an index, like numbers[0] for the first slot.
Dynamically sized arrays are a bit more flexible. You can create an array without specifying the size right away, then decide the size later based on some variable. For example:
int size = getSize(); // some method that returns an int
String[] names = new String[size];
Here, we're creating a String array called "names", but the size comes from calling a method getSize(). This lets you choose the array size dynamically at runtime.
So in summary, simple fixed-sized arrays are preset, while dynamically sized arrays can adapt their size as needed. Both are very useful in different situations accordingly.
Syntax
The basic syntax for creating an array in Java looks like this:
dataType[] arrayName = new dataType[size];
Here's what each part means:
dataType is the type of data the array will hold (like int, String, etc.)
arrayName is the name you want to give your array
size is the number of elements the array will hold
So for example, to create an array of integers called "numbers" with a size of 10, you would write:
int[] numbers = new int[10];
Once you've created your array, you can access and modify elements using square brackets [] and the index of the element you want. Remember, array indexes start at 0! Here's an example:
// Set the value of the first element to 42
numbers[0] = 42;
// Get the value of the third element
int third = numbers[2];
You can also use a loop to work with all the elements of an array. A common pattern is to use a for loop to go through each index:
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
This loop starts i at 0 and goes up to (but not including) the length of the "numbers" array. Each time through, it prints out the element at index i.
Examples
Example 1: Creating & populating an array
// Create an array of strings with size 4
String[] fruits = new String[4];
// Populate the array with values
fruits[0] = "Apple";
fruits[1] = "Banana";
fruits[2] = "Orange";
fruits[3] = "Pear";
// Print out the contents of the array
for (int i = 0; i < fruits.length; i++) {
System.out.println(fruits[i]);
}
Output:
Apple
Banana
Orange
Pear
In this example, we create a String array called "fruits" with a size of 4. We then assign a value to each index of the array. Finally, we use a for loop to print out each element of the array.
Example 2: Finding the sum of an array
// Create an array of integers
int[] numbers = {4, 2, 7, 1, 9};
// Calculate the sum of the array
int sum = 0;
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
// Print out the sum
System.out.println("The sum is: " + sum);
Output:
The sum is: 23
Here, we create an integer array called "numbers" and initialize it with some values. We then use a for loop to go through each element and add it to a running total called "sum". After the loop, we print out the final sum.
Difference between Array and ArrayList
Parameter
Array
ArrayList
Size
Fixed size determined at creation
Dynamic size, can grow or shrink as needed
Performance
Faster for simple operations
Slower than arrays, but offers more flexibility
Syntax
dataType[] arrayName = new dataType[size]
ArrayList<dataType> listName = new ArrayList<>()
Adding Elements
Cannot add elements beyond the initial size
Can add elements using add() method
Removing Elements
Cannot remove elements
Can remove elements using remove() method
Primitives
Can directly store primitives (int, char, etc.)
Cannot directly store primitives, needs wrapper classes
Iteration
Can use loops to iterate (for, while, etc.)
Can use loops or Iterator interface
Type-Safety
Not type-safe, can store any type of object
Type-safe, ensures all elements are of specified type
Length/Size
length attribute gives the size of array
size() method returns the number of elements
Resizing
Cannot be resized once created
Automatically resizes itself as ele
As you can see, arrays and ArrayLists have quite a few differences. Arrays are simpler and faster, but are fixed in size. ArrayLists are more flexible and can dynamically change size, but are a bit slower and require more memory.
The choice between using an array or ArrayList largely depends on your specific needs. If you know the exact number of elements and don't need to change the size, an array is a good choice. If you need flexibility in size and don't mind a slight performance hit, an ArrayList is what you should go with.
Frequently Asked Questions
Can I change the size of an array after it is created?
No, you cannot change the size of an array once it's created in Java. If you need a collection that can change size, consider using an ArrayList instead.
Are ArrayLists as fast as arrays?
ArrayLists are generally slower than arrays. This is because ArrayLists need to resize & potentially copy elements to new locations in memory when they grow or shrink. Arrays, having a fixed size, do not have this overhead & allow faster element access.
How can I choose between using an Array & an ArrayList?
Choose an array if you know the number of elements in advance & it won’t change. Arrays are simpler & faster. Choose an ArrayList if your list size needs to change, or you benefit from methods like add() & remove().
Conclusion
In this article, we've learned the main but important differences between arrays & ArrayLists in Java. We've looked at how each is used, their benefits, & limitations, which has given you the idea that which you need to use in your coding projects. By knowing when to use each type, you can optimize your Java applications for both performance & flexibility, that might improve the performance of your application.