ArrayList in Java

ArrayList in Java is a class which implements the List interface of collection framework. ArrayList is dynamic data structure i.e like Arrays you don’t need to define the size of ArrayList during the declaration. You can add and remove the elements from ArrayList and ArrayList adjust it’s size automatically.

ArrayList can contain the duplicate elements and it’s non-synchronized data structure.


ArrayList vs Arrays 

ArrayList is the best alternative to Arrays in Java as ArrayList is Dynamic data structure and Arrays are the Static data structure. The issue with arrays is that they are of fixed length.

So that we can add elements to Array predefined size. Also, if you remove elements from the Array then memory consumption would be the same as it doesn’t shrink.

On the other hand, ArrayList can dynamically grow and shrink as per the need.


Generic vs Non-Generic ArrayList

Java collection was non-generic before JDK 1.5. Since 1.5, it is generic.

Java new generic collection allows you to have only one type of object in the collection. Now it is type safe so typecasting is not required at run time.


Let’s see the old non-generic example of creating java collection.

Non-Generic ArrayList Example –

 ArrayList angl=new ArrayList();

This is the example of Non-generic ArrayList here we didn’t mention the type of collection.


Generic ArrayList Example –

 ArrayList<String> agl=new ArrayList<String>();

This is the example of Generic ArrayList. Here have declared the Collection type (String) at the time of Initialization.


Example of ArrayList

Let’s see the example of ArrayList and  basic operations on ArrayList.


Elements of the ArrayList are — [10, 15, 20]
Size of ArrayList aftrer Element addition — 3
Size of ArrayList aftrer Element removal — 3
Element: 10
Element: 15


In the above example We have created the ArrayList named ‘elements’ of Integer type then we have added three elements in this ArrayList using add() method of the ArrayList class.

After addition we print the ArrayList then we get the size of ArrayList using size() method of the ArrayList class. After then we removed the element present on the index 2 using remove() method of the ArrayList class and at last we printed the ArrayList elements one by one.

So this is all, how can we implement the ArrayList in java and perform some basic operation on it. In coming tutorials, we will see the other important and interesting concepts of ArrayList class and operation on ArrayList.


Selenium Tutorial:

If you liked this video, then please subscribe to our YouTube Channel for more video tutorials.

0 Comment

Leave a Reply