Example of using ArrayList

In the previous post, we have see how to initialize the ArrayList. In this post, we will example of using ArrayList.

ArrayList is a class which implements List Interface. It is an good alternative of Java Arrays. There are few benefits of using ArrayList over Java Arrays.

  • Java Arrays are of fixed length and if they are full we can not add more elements to it. But ArrayList can dynamically grow. You can add as many as elements you want.
  • If some elements are removed from java array, even after removal memory consumption would be the same as it does not shrink. But ArrayList can be shrink easily as per the need.
  • Apart from this ArrayList provides predefined methods to work on the elements which makes life easy, but this is not the case with array.

Let’s understand the ArrayList and its methods with examples.

1)add method:

This method is used to add objects to the ArrayList.


Example: We are adding cities to the arrayList.


All Bank Names: [Delhi, Bangalore, Pune]

2) add(int index, ObjType element): It allows you to add any element of specific type at the desired index. Index starts from zero (0).


All Bank Names: [Mumbai, Delhi, Bangalore, Pune]


3) remove(Object o): It allows you to remove the specified object.


All Bank Names: [Delhi, Bangalore]


4) remove(int index): It allows to remove the element specified at a particular index at run time.


All Bank Names: [Delhi, Pune]

5) contains(Object o): It verifies that a ArrayList contain the specified object or not and return boolean value true/false.


Object exist : Pune

6) set(int index, Object o): This method allows you to update the object at a particular index.In the below example, we are updating 2nd index value from Bangalore to Mumbai.


All Bank Names: [Delhi, Mumbai, Pune]


7) Object get(int index): It returns the object specified at a particular index.


City at index 1 : Bangalore


8)  int indexOf(Object o): Gives the index of the object o. If the element is not found in the list then this method returns the value -1.


Pune is present at index : 2


9) int size(): It returns the size of the list i.e. number of elements present in the list.


Total Elements : 3


10) clear(): This method will remove all the objects in the list.


Total Elements : 0
Have any question or suggestion for us?Please feel free to post in Q&A Forum
ArrayList in Java
Find size of ArrayList in java
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...

Leave a Reply

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