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<>();
view raw Test.java hosted with ❤ by GitHub

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.*;
view raw Test.java hosted with ❤ by GitHub

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

Adding element

myArrList.add(50);
view raw Test.java hosted with ❤ by GitHub

Getting the size of ArrayList

int size = myArrList.size();
view raw Test.java hosted with ❤ by GitHub

Acquiring the index of given element

int index = myArrList.indexOf(50);
view raw Test.java hosted with ❤ by GitHub

Retrieving the content of specific index

int val = myArrList.get(0);
view raw Test.java hosted with ❤ by GitHub

Traversing ArrayList

for (int i = 0; i < myArrList.size(); i++) {
System.out.println(String.format("Element number %d is: %s", i, myArrList.get(i));
}
view raw Test.java hosted with ❤ by GitHub

Removing all elements of ArrayList

myArrList.clear();
view raw Test.java hosted with ❤ by GitHub

Removing specific element from ArrayList

myArrList.remove(2); //Removing item which has index of 2
myArrList.remove(Object); //Remove the given item from list
view raw Test.java hosted with ❤ by GitHub

Copying elements from one ArrayList to another

List<Integer> tmp = new ArrayList<>();
tmp.addAll(myArrList);
view raw Test.java hosted with ❤ by GitHub

Conversion

From ArrayList to Array

int[] tmpArray = new tmpArray[myArrList.size()];
int[] normalArray = myArrList.toArray(tmpArray);
view raw Test.java hosted with ❤ by GitHub

From Array to ArrayList

List<Integer> newArrList = Arrays.asList(normalArray);
view raw Test.java hosted with ❤ by GitHub

For more information please refer to the links in below.