ArrayLists: Dynamic Arrays in Java (Part 2)

ByBala Manikandan

ArrayLists: Dynamic Arrays in Java (Part 2)

Reading Time: 3 minutes

Here is the second post on ArrayLists which is a continuation from part 1 . Here are some points covered in the first part:

  • Main advantage of ArrayLists over arrays
  • Creating an ArrayList
  • Adding elements to ArrayLists
  • Iterating through the elements
  • Modifying and deleting elements

In the next section, we will deal with some methods commonly used to query an ArrayList.

Querying ArrayLists:

The following example demonstrates the usage of some more ArrayList methods:

//Other methods of ArrayList

package codingexamples;

import java.util.*;


public class ArrayListExample3 {

     public static void main(String[] args){

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




        list.add(1, “Watermelon”);



        String val = list.get(3);     //retrieve element at index 3


          int sz = list.size();










The output of the code is:

[Apple, Watermelon, Banana, Grapes, Apple]








The methods get() and size() used above are self-explanatory, which is evident from the first three lines of output (remember that index 3 is the fourth element). The method contains() returns true if the specified item is present in the list and false otherwise. In this case, the list contains “Banana” but does not contain “String”. And last, the indexOf() and lastIndexOf() methods return the indices of the first and the last occurrences of the specified object, respectively, or -1 if the object is not present. This is consistent with the above output.

The next section deals with a slightly more advanced concept related to ArrayLists.

Role of the equals() method in results of ArrayList methods:

The equals() method of class Object is inherited by all the classes in Java. But by default, it only checks whether the references of the invoking object and the method parameter are the same, or in other words, it returns true only if they refer to the same object. However, classes may override this method and define a new “equality” condition, which usually involves comparison of the instance variables of the objects.

Some of the methods in the ArrayList class, such as remove(), contains(), indexOf() and lastIndexOf() use the equals() method to check if an object is present in the list or not. Thus depending on whether the equals() method is overridden or not, the results of these methods may differ. This is demonstrated in the following code:

//Demonstrating effects of overriding equals() in classes used as the

//element type in an ArrayList

package codingexamples;

import java.util.*;


class Person1{

    private String name;

    Person1(String nm){name = nm;}

    public String getName(){return name;}

    //no equals() override


class Person2{

    private String name;

    Person2(String nm){name = nm;}

    public String getName(){return name;}


    //Override equals(), returns true if the names are equal

    public boolean equals(Object obj){

        if(obj instanceof Person2){

            Person2 other = (Person2)obj;

            boolean isEqual =;

            return isEqual;



            return false;




public class ArrayListExample4 {

    public static void main(String[] args){

        ArrayList<Person1> list1 = new ArrayList<>();

        Person1 p1 = new Person1(“John”);

        Person1 p2 = new Person1(“Roger”);




        System.out.println(list1.contains(p2));                     //prints true

        System.out.println(list1.contains(new Person1(“Roger”)));   //prints false!

        list1.remove(new Person1(“John”));                      //doesn’t remove John!


        for(Person1 p : list1)

            System.out.print(p.getName() + “:”);



        ArrayList<Person2> list2 = new ArrayList<>();

        Person2 p3 = new Person2(“John”);

        Person2 p4 = new Person2(“Roger”);




        System.out.println(list2.contains(p4));                    //prints true

        System.out.println(list2.contains(new Person2(“Roger”)));  //also prints true!

        list2.remove(new Person2(“John”));                         //removes John


        for(Person2 p : list2)

            System.out.print(p.getName() + “:”);




The output of the code, as it turns out, is:







The above code defines two almost identical classes, Person1 and Person2, both of which have a single instance variable, name. But Person1 does not override equals(), whereas Person2 does. In case it is tough to understand the code in the equals() override of class Person2, for now just remember that the new definition returns true if the names of the two Person2 objects are the same.

Now an ArrayList of Person1 objects is created and two Person1 objects with names John and Roger are added to it. If the ArrayList is queried whether it contains the object referenced by p2 (that is, ‘Roger’), it results in true. But if instead you pass a new object whose ‘name’ is also Roger to the contains() method, it results in false! Why? Because Person1 did not override equals(), and thus only object references were compared all along! Similarly, the next line demonstrates an unsuccessful (for the very same reason) attempt to remove ‘John’ from the list. This is demonstrated in the third line of output, which displays the ‘names’ of all the elements in the list.

The same things are done for another ArrayList of Person2 objects, and a significant change is observed in the output, only because Person2 overrode equals(), and so names instead of object references were compared! Thus the second call to contains() on the second list also produced true, and this time John was successfully removed from the list.

We have seen how to use ArrayLists in Java in this post – stay tuned for more technical posts!

About the author

Bala Manikandan author

Bala Manikandan is a first-year engineering student of the Indian Institute of Technology, Roorkee! He is an Oracle certified Associate(OCAJP 8) Bright and Intelligent, Computers and Math are his favorite subjects! He hopes to do path breaking research in the Computer Science field!

Leave a Reply