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 ArrayList. 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.

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

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;

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=0;
 Size=myArrList.size();

Acquiring the index of given element:

 int Index=0;
 Index=myArrList.indexOf(50);

Retrieving the content of specific index:

 int Val=0;
 Val=myArrList.get(0);

Traversing ArrayList:

 for(int i=0;i<myArrList.size();i++)
 System.out.println("Element at" +i+"index ="+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:

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

Conversion:
From ArrayList to Array

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

From Array to ArrayList

 ArrayList newArrList=Arrays.asList(normalArray);

For more information please refer to the links in below.
Generic in Java
Java collection
Oracle ArrayList documentation

send your idea and information to kasra.madadipouya@geeksweb.eu.org

Leave a Reply