Categories
Java

Dynamic array in Java

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.

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.

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

Adding element

Getting the size of ArrayList

Acquiring the index of given element

Retrieving the content of specific index

Traversing ArrayList

Removing all elements of ArrayList

Removing specific element from ArrayList

Copying elements from one ArrayList to another

Conversion

From ArrayList to Array

From Array to ArrayList

For more information please refer to the links in below.

Exit mobile version