WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Java Collections · Basic · question 12 of 100

What is the purpose of the equals() method in Java Collections?

📕 Buy this interview preparation book: 100 Java Collections questions & answers — PDF + EPUB for $5

In Java Collections, the equals() method is used to compare two objects for equality. It is defined in the Object class, which is the base class for all Java classes, and is therefore inherited by all Java classes, including those that implement the Collection interface.

The equals() method is used to test whether two objects are equal or not. In the context of collections, it is used to test whether two collections have the same elements or not. The method returns true if the two objects are equal, and false otherwise.

The default implementation of the equals() method in the Object class simply checks whether two objects are the same object (i.e. whether they have the same memory address). However, in order for the equals() method to be useful in comparing collections, it must be overridden in the classes that implement the Collection interface.

For example, the ArrayList class overrides the equals() method to compare two ArrayLists for equality. Two ArrayLists are considered equal if they have the same size and contain the same elements in the same order. Here’s an example:

import java.util.ArrayList;

public class Example {
    public static void main(String[] args) {
        // create two ArrayLists with the same elements
        ArrayList<Integer> list1 = new ArrayList<>();
        list1.add(1);
        list1.add(2);
        list1.add(3);
        
        ArrayList<Integer> list2 = new ArrayList<>();
        list2.add(1);
        list2.add(2);
        list2.add(3);
        
        // compare the two ArrayLists for equality
        boolean result = list1.equals(list2);
        System.out.println(result); // prints "true"
    }
}

In this example, we create two ArrayLists called "list1" and "list2" with the same elements. We then use the equals() method to compare the two ArrayLists for equality, and print out the result.

The output of this program would be:

true

As you can see, the equals() method correctly determines that the two ArrayLists are equal.

In summary, the purpose of the equals() method in Java Collections is to compare two objects for equality, and it is important to override this method in classes that implement the Collection interface in order to compare collections for equality.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Java Collections interview — then scores it.
📞 Practice Java Collections — free 15 min
📕 Buy this interview preparation book: 100 Java Collections questions & answers — PDF + EPUB for $5

All 100 Java Collections questions · All topics