Dynamic array in Java

Default featured post

In the past I discussed about dynamic memory allocation and dynamic array in C programming language. In addition, I put examples for all explained methods. In this post I will cover dynamic memory allocation or more precisely dynamic array in Java.

For recall dynamic array is useful when you do not know the number of elements which you may need on run time. This means that the number of elements might be changed in run times more than one or is totally unknown before run time. By contrast of C, in Java dynamic array is easy to create and manipulate by using collection (generic). In Java there is a specific collection for creating dynamic array which is known as java.util.ArrayList and java.util.LinkedList are derived from java.util.List interface which is really powerful with high flexibility.

The following line demonstrates how to define ArrayList in Java applications.

List<Integer> myArrList = new ArrayList<>();

The above line creates array list named ‘x’ which is integer type. One important thing is that, you should import ArrayList class before using it by following line.

import java.util.ArrayList;
import java.util.List;
// OR
import java.util.*;

Now take a look at ArrayList (generally List) methods.

Adding element

myArrList.add(50);

Getting the size of ArrayList

int size = myArrList.size();

Acquiring the index of given element

int index = myArrList.indexOf(50);

Retrieving the content of specific index

int val = myArrList.get(0);

Traversing ArrayList

for (int i = 0; i < myArrList.size(); i++) {
    System.out.println(String.format("Element number %d is: %s", i, myArrList.get(i));
}

Removing all elements of ArrayList

myArrList.clear();

Removing specific element from ArrayList

myArrList.remove(2); //Removing item which has index of 2
myArrList.remove(Object); //Remove the given item from list

Copying elements from one ArrayList to another

List<Integer> tmp = new ArrayList<>();
tmp.addAll(myArrList);

Conversion

From ArrayList to Array

int[] tmpArray = new tmpArray[myArrList.size()];
int[] normalArray = myArrList.toArray(tmpArray);

From Array to ArrayList

List<Integer> newArrList = Arrays.asList(normalArray);

For more information please refer to the links in below.