July 25, 2021

ArrayList in Java

ArrayList is an resizable-array implementation of the List interface. This class uses a dynamic array for storing elements, including null value.

package com.chetasmind.listPackage;

import java.util.ArrayList;

public class ArrayListExample {

	public static void main(String[] args) {

		ArrayList obj = new ArrayList();
		
		obj.add("hello");
		obj.add(5);
		obj.add(null);
		obj.add(9);
		obj.add(8.88);
		
		for(int i=0;i<obj.size();i++) {
			System.out.println(obj.get(i));
		}
	}
}

In line no.9 I have created a ArrayList object. Then adding the different elements: String, integer, null to this object. Getting each value by iterating the arraylist object using for loop.

If you have written above code in some IDE like Eclipse or intellij, you might have observed the warning in the line: ArrayList obj = new ArrayList(); saying: ArrayList is a raw type. References to generic type ArrayList<E> should be parameterized. Note: Application will be compiled properly. But we need to check about this warning too.

Just imagine, you want to store only String objects in Arraylist and if you try to save other than String objects in Arraylist, during compile time you should get that error !! Sound great right. In this case, create the Arraylist object as shown. ArrayList<String> obj = new ArrayList<String>();

package com.chetasmind.listPackage;
import java.util.ArrayList;

public class ArrayListExample {

	public static void main(String[] args) {

		ArrayList<String> obj = new ArrayList<String>();
		 
		obj.add("hello");
		obj.add("hi");
		obj.add(5);
		obj.add("welcome"); 
		
		for(int i=0;i<obj.size();i++) {
			System.out.println(obj.get(i));
		}

	}
}

Line no. 11 will throw error. Since ArrayList object obj will accept only String value.

From Java 7 onwards, instead of creating the object in this way: ArrayList<String> obj = new ArrayList<String>(); we can use diamond operator: ArrayList<String> obj = new ArrayList<>();

The above application is also present in my github repository.
If you are writing java applications for the first time, refer my Project structure article.

Leave a Reply

Your email address will not be published. Required fields are marked *