Why Do We Use Collections Instead of Arrays?

java dev.to

If you notice while working with arrays, the size is always fixed. Once you create an array, you can’t directly increase or decrease its size.

Because of that, even for a small change like adding or removing an element, we end up creating a new array and copying all the values. It works, but it feels a bit unnecessary when the data keeps changing.

Let’s see a simple example.

Using Array

int[] arr = {10, 20, 30};

// creating a new array with extra space
int[] newArr = new int[arr.length + 1];

// copying old values
for(int i = 0; i < arr.length; i++) {
    newArr[i] = arr[i];
}

// adding new value
newArr[arr.length] = 40;
Enter fullscreen mode Exit fullscreen mode

Here, just to add one element, we had to create a new array and copy everything manually.

Using Collection (ArrayList)

Now look at the same thing using ArrayList:

import java.util.*;

ArrayList<Integer> list = new ArrayList<>();

list.add(10);
list.add(20);
list.add(30);

// adding new value
list.add(40);
Enter fullscreen mode Exit fullscreen mode

That’s it. No extra steps, no copying needed.

Removing Element

With arrays:

int[] arr = {10, 20, 30, 40};

int[] newArr = new int[arr.length - 1];
int j = 0;

for(int i = 0; i < arr.length; i++) {
    if(arr[i] != 30) {
        newArr[j++] = arr[i];
    }
}
Enter fullscreen mode Exit fullscreen mode

With ArrayList:

list.remove(Integer.valueOf(30));
Enter fullscreen mode Exit fullscreen mode

Much simpler and cleaner.

Since When Is This Available?

Collections were introduced in Java 1.2, and since then they’ve been widely used in real-world applications.

Final Thought

Arrays are still useful when the size is fixed and known.

But if your data changes often, collections make things easier. Less code, fewer steps, and more flexibility.

Source: dev.to

arrow_back Back to Tutorials