ArrayList in Java

ArrayList

In the previous blog we learned about the Object class in Java. If you want to know more about the Object class then click on Object Class in Java. In this blog, we will learn about the ArrayList in Java. In C and C++ the size of arrays is fixed at compile time only, we cannot change it. Suppose there is a department in each department there will be not more than 100 students. But what if one department has 150 students, then defining an array of 150 for every department is not a good way, because just for 1 department we will have to define an array of 150 which is not an appropriate solution. To overcome this, Java allows to set the size of an array at runtime.

e.g.

int actualSize = . . .;
var staff = new AtrowelStudent[actualSize];

But the above statement doesn’t completely solve the problem of dynamically modifying the array at runtime. Once the size of an array is set we cannot change size of an array easily. But we can deal with this with another approach in Java which is called ArrayList. ArrayList is similar to an array, but it has the ability to adjust its capacity when the elements are added or removed, no extra code is required. We will go through ArrayList in detail:


ArrayList Declaration

If we want declare an ArrayList of Student object, then we can do it by the following way:

var atrowelStaff = new ArrayList<AtrowelStudent>();

If we don’t want to use the var keyword, then we can eliminate the type parameter on the right -hand side:

ArrayList<AtrowelStudent> staff = new ArrayList<>();

The above syntax is called diamond syntax because the empty brackets(<>) depict a diamond. The compiler checks what happens to the new value. If the new value is assigned to a variable, passed into a method, or returned from a method, then the compiler checks the generic type of the variable, parameter, or method. It places that particular type into the diamond(<>). In the above example, the new ArrayList<>() is assigned to a variable of type ArrayList <AtrowelStudent>. Therefore, the generic type is AtrowelStudent.


Methods

  1. add() - We use the add() method to add the elements into an array list. Following is the example for populating the array list:
  2. atrowelStaff.add(new AtrowelStudent("Willam", . . .));
    atrowelStaff.add(new AtrowelStudent("Johnson", . . .));

    It(array list) manages an internal array of object references. It is obvious that after some time the array will not have space i.e. it will run out of space. This is when the ArrayList plays an important role. If we call add() method and suppose if the internal array is full, then the array list automatically creates a bigger array and copies all the objects from the smaller to the bigger array.

  3. ensureCapacity() - If we know the count of elements to be stored i.e. if we know how many elements will be stored, then we can use the ensureCapacity() method. For example
  4. atrowelStaff.ensureCapacity(200);

    We can also initial capacity to the ArrayList . For example:

    ArrayList<AtrowelStudent> atrowelStaff = new ArrayList<>(200);
  5. size() - The size method returns the actual number of elements in an array list.
  6. e.g.

    atrowelStaff.size();

    It returns the number of elements in the atrowelStaff array list. It is the same as using the length() method.

    e.g.

    atrowelStaff.length();

Summary of Methods used in ArrayList

MethodsDescription
boolean add(AtrowelEmployee obj)It appends obj at the end of the array list and always returns true.
int size()It returns the number of elements currently stored in the array list.
void ensureCapacity(int capacity)It ensures that the array list has the capacity to store the given number of elements without reallocating its internal storage array.
void trimToSize()It reduces the storage capacity of the array list to its current size.

Accessing ArrayList Elements in Java

Accessing the array elements from an ArrayList is not an easy task. It follows a complex syntax for accessing the elements. The reason behind it is that the ArrayList class is not a part of the Java programming language; it is a utility class programmed by someone and supplied in the standard library. In order to access the elements from the ArrayList get() method and set() method is used. For example, to set the particular element i.e. ith element we use:

atrowelStaff.set(i, atrowel);

The above statement is equivalent to:

atrowelStaff[i] = atrowel;

Sometimes we get the growth flexible growth and convenient element access by just using the following trick: First, we have to make an array list and add all the elements:

var atrowelList = new ArrayList<AtrowelEmployee>();
while (. . .){
  atrowelVar = . . .;
  list.add(atrowelVar);
}

Once the above step is done, use the toArray method to copy the elements into an Array:

var atrowelVar1 = new AtrowelEmployee[atrowelList.size()];
atrowelList.toArray(atrowelVar1);

Sometimes the situation occurs where we have to add elements in the middle of an array list, then we can use the add method with an index parameter:

int atrowelNo = atrowelStaff.size() / 2;
atrowelStaff.add(atrowelNo, atrowelEmployee);

The elements at locations atrowelNo and above are shifted up, in order to make some space for new entry. Suppose if the new size of an array list after insertion exceeds the capacity, then the array list can reallocate its storage array. We can also remove an element from the middle of an array list by using the following method:

AtrowelEmployee atrowelEmployee = atrowelStaff.remove(atrowelNo);

For traversing the content of an array list we can use for each loop. For example:

for (AtrowelEmployee atrowelEmployee : atrowelStaff){
  ...
}

The above statement behaves same as the for loop i.e.:

for (int i = 0; i < atrowelStaff.size(); i++){
  AtrowelEmployee atrowelEmployee = atrowelStaff.get(i);
  ...
 }

e.g.

import java.util.*;
public class ArrayListExample{
  public static void main(String[] args){
    var atrowelStaff = new ArrayList<AtrowelEmployee>();
    atrowelStaff.add(new AtrowelEmployee("Jackson", 85000, 1982, 10, 15));
    atrowelStaff.add(new AtrowelEmployee("Smith", 80000, 1979, 10, 15));
    atrowelStaff.add(new AtrowelEmployee("Willam", 90000, 1978, 10, 15));
    for (AtrowelEmployee e : atrowelStaff)
      e.raiseSalary(5);
    for (AtrowelEmployee e : atrowelStaff)
      System.out.println("name=" + e.getName() + ",salary=" + e.getSalary()
    + e.getHireDay());
  }
}

Summary of Methods used in ArrayList for accessing elements from the array list

MethodsDescription
AtrowelEmployee set(int index, AtrowelEmployee atrowelObj)It puts the value atrowelObj in the array list at the specified index, returning the previous contents.
AtrowelEmployee get(int index)It gets the value stored at a specified index.
void add(int index, AtrowelEmployee atrowelObj)It shifts up elements to insert atrowelObj at the specified index.
AtrowelEmployee remove(int index)It removes the element at the given index and shifts down all elements above it and returns the removed element.

Core Java Tutorial

Get in Touch

Atrowel will be pleased to receive your feedback and suggestions. Those of you who would like to contribute, please send us an email.