How to work with ArrayLists in Java? Let’s deep dive

Learn what is ArrayList, why we use and how to use it

Mitadru Datta
Javarevisited
8 min readAug 23, 2021

--

Image by OpenClipart-Vectors from Pixabay

ArrayLists are used more often than the standard array of a fixed size. If you are a Competitive Programmer, or want to be one, then you must understand and have a clear concept of ArrayLists as you will be using it everytime you take some input for a specified problem.

Before jumping directly to ArrayLists, I want to give you a glimpse of the standard array so that it will be much more clearer to understand the challenges faced by it and the need to use ArrayList.

Working with arrays:-

When we speak about arrays in Java or any other programming language the most common format or syntax that comes into our mind is quite similar to this:-

int[] arr = new int[5];

This is the syntax used to create an array in Java of fixed size.
Here,

  • arr -This is the reference variable that will be pointing to an array object in the heap memory
  • int[] -This is specifying the data type of the elements that will get stored in the array object. For example, here, all the elements in the array arr has to be of int datatype.
  • new -This is a keyword used when we want to create a new object. Here, simply saying, we are creating a new array
  • int[5] -This means we are creating an array with a fixed size or length 5. We can store or rather to say array can point to 5 integer values only with an index value range of 0–4.

Drawbacks of the standard array :-

  • Fixed size — The size or length of the array has to be specified at the very beginning, that is at the time of array initialization. Once, assigned a fixed size, it can’t be changed at any point in the program execution. If we try to insert or cross the fixed size limit, extra values will not get added to the array or an error will be thrown.
  • Cannot remove elements, only replace — Once we start filling the array, and it becomes completely filled, we can only replace an existing element in some index position with a new element. We can’t remove the element with adding new one and also the size of the array remains constant throughout the process.
  • Internal array operation is tedious and time-consuming — Suppose you want to check whether a particular element is present inside the array or not. For this, you have to iterate over every value or use some in-built Java methods. To find the max and min value, again iterate.

This type of array is very difficult to use when the number of elements to be inserted in it cannot of decided at the beginning, and is completely user dependent.

Also, if you are reading from a pretty large file, it is very difficult to determine the total number of lines, hence, the size of the array in which each element is a String representing each line in the file, can’t be specified.

There are many more instances, where, standard arrays are not used for carrying out operations of storing similar types of values.

In such cases, ArrayLists are used.

Photo by Christina Morillo from Pexels

Initializing an ArrayList:-

As we have mentioned the necessity or why we use ArrayLists, let’s now focus on the part of how to use it.

Starting with the syntax, an ArrayList is defined or initialized in the form:-

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

Now, let’s dig deep and understand each part one by one:-

  • list — The reference variable, which is used to point to an object made from the class ArrayList .
  • ArrayList<Integer> — Here, ArrayList means, the object that the reference variable list is pointing to is made from, or belongs to the class named ArrayList . In simple words, ArrayList is the data type of the reference variable list .
  • <Integer> — This is a Generic which is used to specify that this ArrayList can only store values which are of Integer datatype. If you don’t know what are generics, I will be covering this in my upcoming articles.
    Another point worth mentioning is that we can’t include primitive datatypes like int, char, boolean inside the generics. We can only include wrapper classes like Integer. We can use or specify String, as it is not a primitive datatype.
    The program will still run if we don’t include the generics, but, it is a good practice to use one as and when required.
  • new ArrayList<>(5) — The new keyword is already discussed, when explaining the standard array. The portion ArrayList here is calling the constructor of the class ArrayList in order to create an object of the class ArrayList . The (5) is used to specify the initial capacity of the ArrayList. Though, it will still work if we don’t specify or cross the initial capacity, but, it is a good practice to specify at the time of initialization.

As we covered the syntax part, let’s now get accustomed with all the beautiful methods, that the class ArrayList provides, for carrying out array operations like adding a new element, removing, checking the presence of an element, modifying or replacing an existing element with a new one and so on.

Methods used frequently when working with ArrayLists :-

  1. Adding new elements — To add elements to the ArrayList we use methods:-
    i) .add(Object) :- This creates or adds a new element at the end of the ArrayList.
    ii) .add(int index, Object) :- This adds an element in the specified index position and shift all the other elements one place to the right after this specified index value. If the last index value is less than the specified one, then the new element gets added to the last of the array.
  2. Replacing an existing element :- If we want to modify or update or replace a already present element with a new one, then we use :-
    i) .set(int index, Object) :- This will set a new element in the specified index position and replacing the existing one.
  3. Removing an existing element :- In order to delete or completely remove an element we use:-
    i) .remove(Object) — This will remove the specified object or element from the ArrayList. If more than one element or object exists in the ArrayList, then the one encountered first or rather to say the least index value gets removed.
    ii) .remove(int index)- This will remove the element present at the specified index position. All the elements present after the specified index value will get shifted one place to the left. Here the actual array size gets reduced.
  4. Fetching an object or element:- In order to fetch an object or element present in the ArrayList we use:-
    i) .get(int index)- This is used to get an object or element present in the specified index position. Note that when working with ArrayLists, we can’t use or write something like arr[3] to get the value at index position 3. This is not allowed.
  5. Checking the existence of a particular element :- If we want to check whether a particular element or object is present in the ArrayList or not we use :-
    i) .contains(Object) — This will return a boolean value i.e. true if the element is present and false if the element or object can’t be found in the ArrayList. No Need to iterate over the entire array!!
  6. Fetching the index value of an element :- If we want to know the position or index value of an element or object in the ArrayList, we use:-
    i) .indexOf(Object) — This will return an integer value which is the index value or position of the specified element or object. If the given object or element can’t be found in the ArrayList, then this will return -1. So, this can also be used as an alternative to the .contains(Object) method.

Now, let’s incorporate all of this methods we’ve learnt so far into a single program to understand more clearly how all of them work.

ArrayList<Integer> list = new ArrayList<>(3);
list.add(15);
list.add(35);
list.add(47);
list.add(13);
list.add(17);
System.out.println(list); // [15, 35, 47, 13, 17]
int a = list.indexOf(47);
System.out.println(a); // 2
int num = list.get(1);
System.out.println(num); //35
System.out.println(list.contains(45)); // false
list.set(3, 72);
System.out.println(list); // [15, 35, 47, 72, 17]
list.remove(17);
System.out.println(list); // [15, 35, 47, 72]
list.add(1, 98);
System.out.println(list); // [15, 98, 35, 47, 72]

Another point worth mentioning is that we don’t need to write something like Arrays.toString(arr) in order to convert the array to String first and then print the elements of the array all together.
ArrayList does that internally !!

Are ArrayLists really of Unlimited size ?

Image by Gordon Johnson from Pixabay

The answer is a big No.

Though, it may appear as if we can continue to add as many elements or objects we want in a particular ArrayList, but internally we get a very different picture.

Visualize with a simple example :-

You can visualize it like, as if, after initialization of an ArrayList, JVM creates an array in the heap memory of some fixed length, say n.

Now, we start adding elements or objects into a particular ArrayList. After the array gets filled or reached a certain value say m (internal algorithm), for explanation purpose, let’s say 50%, a new array gets created, double of the previous array size, i.e. 2n .

All the elements or objects present in the original or previous array, gets copied to this newly created array.

After, all the elements gets copied, the previous array gets deleted. This new array will now start taking up new elements up to a certain value and then the entire process gets repeated.

Note from Author :-

Photo by Markus Winkler on Unsplash

If you have read all the content and reached so far, then congratulations !!

Now, I hope, you have get a complete knowledge of ArrayLists in Java, how it works, and also cleared the misconception that many have regarding the ArrayList’s size or the maximum length to be precise.

You can check out my previous article on Java :-

Do follow me on Medium for more such articles on Java, where I will be covering a topic from scratch and dig deeper into the topic by explaining all the core concepts step by step.

Feel free to comment down below, if you want me to add some more information on this article. You can also suggest any topic related to programming that you want me to cover and I will be more than happy to write on those topic and share my knowledge to others.

--

--

Mitadru Datta
Javarevisited

Writes about Android & Web Dev, Machine Learning, Cloud, contributing to open source. Concern about Health & Psychology, work culture. Loves food, travelling.