Let’s Do It PL
Published in

Let’s Do It PL

Let’s Do It PL

Arrays vs ArrayList

With explanation and comparison in Java

Any person who has any experience with coding should have run into the “Arrays” term. But what are these Arrays we talking about? Why do we need them?

Arrays are basically Objects that hold a fixed number of values in a singular type. This means we can store numerical values like integers but we cannot store integer values with characters. But why do we need them? Actually, many companies have to store lots of information in their codes and do many manipulations on these.

In these times coding language creators or developers have to solve these problems and their response was the “Array” solution. With an array, we can store a lot of variables in the same object and call them whenever we need it easier than declaring them one by one.

But then what is an “ArrayList”? As we all know technology is growing faster than anything but new technologies need new tools and new ways to grow. Yes, Arrays are lifesavers for coding most of the time, or they were. But Arrays have some limitations and these usually cause problems. As we said before, coding language developers had to solve that problem and came up with “ArrayList”.

ArrayLists are very similar to Arrays but they have more freedom and are easier to use. Let’s compare the two to understand better:

1-Capacity

When declaring an Array, we should specify the capacity or the compiler throws an error. If you noticed in the definition, there is a “fixed number of values” phrase. At first sight, someone might think “What is the problem here?” but it is usually a problem. Let’s create one as an example:

int[] arrayOfSales = new int[1000];

Let’s suppose, we are writing a code that stores all of our company’s sales and we want to put all information into an Array because they are created for this purpose, right? For that, we created an Array that has high capacity but the question is: What is going to happen when we reach the maximum capacity? It becomes a disaster because usually we cannot guess these numbers and we actually should not. Array’s capacity isn’t changeable later so it makes it harder to solve afterward.

Then how do developers fight these problems nowadays? The answer is: “ArrayLists”. Because ArrayLists have infinite capacity. Cool, isn’t it? Let’s solve the same problem with ArrayList.

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

Do we see any numbers? No, because there is no limit. We do not have to think about any maximum limit for our sales. What if we want to limit our sales? Then, we can declare an initial capacity in ArrayList or just use an Array.

2-Usage and Methods

Arrays and ArrayLists have the same purpose which is to store information. Arrays use the “=” operator for adding an element such as declaring a variable.

arrayOfSales[0] = 12;
arrayOfSales[1] = 25;

If we want to add a bunch of information then for loop is a good choice.

for(int i=0; i<arrayOfSales.length; i++){
arrayOfSales[i] = scan.nextInt();
}

Adding an element is easy but what about removing it? Removing is a headache in arrays. We need a long code and another array. Of course, there are many other algorithms but it’s usually done by creating an extra array. Here is a single algorithm for that action:

public int[] remove(int[] array, int index){
int[] newArray = new int[array.length - 1];

for (int i = 0, j= 0; i < array.length; i++) {
if (i == index) {
continue;
}
newArray[j++] = array[i];
}
return newArray;
}

It is the most common way to remove an element in an array. There are always different ways to solve a problem but it most likely wouldn’t be shorter than this. It is a long solution for a very basic action. It is usually not worth it at all to spend time on it.

What about sorting in ascending or descending order, swapping 2 elements, shuffling, finding maximum or minimum element? There are a lot of things we want to do with arrays and insides but Arrays take a lot of our time when we need these actions.

On the contrary, ArrayLists have many different methods to facilitate their use. Let’s look at how to add an element to an ArrayList.

listOfSales.add(12);
listOfSales.add(25);

Like we do in Arrays, we can add multiple elements to an ArrayList by using loops. We can use for loop or for-each loop for both Arrays or ArrayLists. Let’s use for-each loop this time:

for (int sale : listOfSales) {
listOfSales.add(scan.nextInt());
}

Until now, we can say that it is really similar to Arrays but what about removing an element?

listOfSales.remove(1);

Awesome, isn’t it? We just changed an 11 line code into 1 line code. ArrayLists also extend the “Collections” class so they have various good methods to use also from that class. Let’s check some of them out.

ArrayList<String> list1= new ArrayList<>();
ArrayList<String> list2= new ArrayList<>();
list1.set(0, "Mike"); //Changed 1st value with "Mike"
list1.addAll(list2); //Adds list2 to list1
list2.clear(); //Removes all elements in list2
Collections.sort(list1); //Sorts all elements in list1 asc
Collections.shuffle(list1); //Shuffles all elements in list1
Collections.reverse(list1); //Reverse order of list1
Collections.swap(list1, 2, 6); //Swaps 3rd and 7th elements
//P.S.: In Java, index starts with 0

Looks definitely easier and less complex, right?

3-Performance

Performance and speed are important factors for deciding which method to use. About that, Arrays perform better than ArrayLists. But why? Arrays have fixed sizes as we remember. Besides, ArrayList resizes itself and this operation slows its performance. Furthermore, ArrayLists can hold only Objects, and they usually store more place than Arrays. Even though Arrays are faster than ArrayLists, fast execution consumes more memory than ArrayList. Of course, these numbers rarely affect seconds but faster is always better.

4-Type Safety

Type safety is a very important part of coding. If we were to explain without giving a complex definition, type-safe languages do not allow the developer to use a different type of elements to use or store together. Arrays are type-safe data structures because they can store only singular data type. ArrayLists do not count as type-safe data structures unless they use Generics (“<>”) along with them. Let’s explain with an example:

String[] students = new String[10];
students[0] = "Mike";
//students[1] = 10; --> gives an error

An Array that stores only String cannot store an integer, it would obviously give an error. That makes Arrays type-safe data structures. But what about ArrayLists? Let’s take a look:

ArrayList teachers = new ArrayList();
teachers.add("Kenny");
teachers.add(12); //does this throw an error?

We created an ArrayList object without using Generics. This creates an ArrayList with no restriction to any type. Therefore, that code does not throw any errors. Again, it might seem like an advantage but no, it makes ArrayLists uncomfortable to use. Let’s suppose, we would like to do some calculations on that ArrayList and we do not know which element is in which type. We cannot perform any mathematical calculation with Strings so we have to use Generics to solve this issue:

ArrayList<String> teachers = new ArrayList();
teachers.add("Levi");
//teachers.add(24); --> gives an error

That’s it. Now, our ArrayList has a restriction to have only a single type to store. That’s how we should use it because type-safety is an important factor that developers should seek.

Summary

Arrays and ArrayLists can be alternatives to each other but most of the developers stopped using Arrays mostly because of the size problem that they bring. Performance and other problematic sides of ArrayLists are completely ignored because they are less complex and easier to use. In many applications, ArrayLists are preferred to use because they save much time during the development phase and let developers break their limits. They both have some advantages and disadvantages and the decision is always up to the developer.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store