Collections Used in an Automation Project

The collections used in a Selenium project, along with their real-world usage:

ArrayList

A dynamic array that can grow or shrink as needed.

Uses:

Advertisement
  • Store a collection of web elements.

  • Store test data.

  • Add, remove, and access elements dynamically.


HashMap

A key-value pair collection used for storing and retrieving values based on keys.

Uses:

  • Store data in property files as key-value pairs.

  • Map elements with their attributes or properties.

Real-time Example

In our project, we create a property file, and here we used the HashMap concept as we have to store data as key-value pairs.


HashSet

Stores unique elements without maintaining insertion order.

Uses:

  • Store unique web elements.

  • Eliminate duplicate values.

  • Handle browser window handles.

Real-time Example

When we deal with window handles, that's where the Set concept comes in because getWindowHandles() returns a Set<String>.


List

An interface that provides an ordered collection with index-based access.

Uses:

  • ArrayList is the most common implementation.

  • findElements() returns a List<WebElement>.


Map

An interface that provides key-value mapping.

Common Implementation

  • HashMap


Making an Immutable Class

An immutable class is a class whose instances cannot be modified after creation.

Benefits

  • Thread safety

  • Simplicity

  • Better performance

Rules for Creating an Immutable Class

  • Declare the class as final.

  • Make all fields private.

  • Do not provide setter methods.

  • Make mutable fields final.

  • Initialize all fields using a parameterized constructor (or a static factory method).

  • Perform a deep copy of mutable fields such as arrays and collections.

  • Return copies of mutable fields from getter methods.

// An immutable class that represents a person
public final class Person {

    // All fields are private and final
    private final String name;
    private final int age;
    private final String[] hobbies;

    // A parameterized constructor that initializes all the fields
    public Person(String name, int age, String[] hobbies) {
        this.name = name;
        this.age = age;

        // Perform a deep copy of the hobbies array
        this.hobbies = hobbies.clone();
    }

    // Getters return copies of mutable fields
    public String[] getHobbies() {
        return hobbies.clone();
    }
}

final vs finally vs finalize

final

Used to declare variables, methods, or classes as unchangeable.

Final Variable

Its value cannot be modified once assigned.

Final Method

Cannot be overridden in subclasses.

Final Class

Cannot be extended or inherited.


finally

A block used with exception handling.

Its code executes whether or not an exception occurs.

Commonly used for:

  • Closing resources

  • Releasing locks

  • Cleanup activities


finalize

A method invoked by the Garbage Collector before reclaiming an object.

Historically used for cleanup.


Abstract Class vs Interface

Abstract Class Interface
Can have abstract and non-abstract methods Only abstract methods (since Java 8, also default and static methods)
Doesn't support multiple inheritance Supports multiple inheritance
Can have final, non-final, static, and non-static variables Has only static and final variables
Can provide the implementation of an interface Cannot provide the implementation of an abstract class
Uses the abstract keyword Uses the interface keyword

Selenium Example

WebDriver is an interface.

Browser classes implement the WebDriver interface.

The interface defines the contract, while browser classes provide the implementation.


Are All Methods in an Abstract Class Abstract?

No.

An abstract class can contain:

  • Abstract methods

  • Non-abstract (concrete) methods

It can even contain zero abstract methods.

Abstract methods must be implemented by concrete subclasses.


Multiple Inheritance in Java (Diamond Problem)

Java does not support multiple inheritance of classes.

Reason

The Diamond Problem occurs when multiple parent classes contain methods with the same signature, making it ambiguous which implementation should be inherited.

Java's Solution

A class can implement multiple interfaces.

This is exactly how Selenium browser driver classes implement several interfaces simultaneously.


Method Overloading in WebDriver Context

Method overloading means using the same method name with different parameter lists.

Example

public class MethodOverloadExample {

    // Overload 1: Enter text into a WebElement
    public static void enterText(WebElement element, String text) {
        element.clear();
        element.sendKeys(text);
    }

    // Overload 2: Locate using By and enter text
    public static void enterText(WebDriver driver, By locator, String text) {
        WebElement element = driver.findElement(locator);
        element.clear();
        element.sendKeys(text);
    }

    public static void main(String[] args) {

        WebElement usernameField =
                driver.findElement(By.id("username"));
        enterText(usernameField, "myUser");

        WebElement passwordField =
                driver.findElement(By.id("password"));
        enterText(passwordField, "secret");
    }
}

Selenium Example

Selenium itself uses method overloading.

Example:

  • frame(int)

  • frame(String)

  • frame(WebElement)


Working with ArrayList

The following example demonstrates:

  • Creating an ArrayList

  • Adding elements

  • Accessing elements

  • Removing elements

  • Iterating

  • Getting the size

public class ArrayListExample {

    public static void main(String[] args) {

        // Create an ArrayList
        ArrayList<String> names = new ArrayList<>();

        // Add elements
        names.add("Alice");
        names.add("Bob");
        names.add("Charlie");

        // Access an element
        String firstElement = names.get(0);

        // Remove an element
        names.remove(2);

        // Iterate
        for (String name : names) {
            System.out.println(name);
        }

        // Size
        int size = names.size();
    }
}

Comparing Strings in Selenium

Using equals()

driver.get("http://example.com");

// Get actual value
String actualValue =
driver.findElement(By.id("elementId")).getText();

String expectedValue = "Expected Text";

// Compare
if (actualValue.equals(expectedValue)) {
    System.out.println("Values match");
}

Using assertEquals()

import org.testng.Assert;

Assert.assertEquals(actualValue, expectedValue);

Difference

  • equals() returns a boolean.

  • assertEquals() automatically fails the test if values do not match.

Note

== compares object references, not string content.

Always use equals() for comparing strings.


Verifying a Sorted List on a Web Page

To verify that numbers appear in ascending order:

  • Retrieve the numbers.

  • Convert them into a list.

  • Compare each value with the previous one.

public class AscendingOrderCheck {

    public static void main(String[] args) {

        driver.get("http://example.com");

        // Locate the list
        WebElement numberListElement =
                driver.findElement(By.id("numberListId"));

        // Split into numbers
        String numberListText =
                numberListElement.getText();

        String[] numbersArray =
                numberListText.split("\\s+");

        // Convert into List<Integer>
        List<Integer> numbersList =
                new ArrayList<>();

        for (String s : numbersArray) {
            numbersList.add(Integer.parseInt(s));
        }

        // Verify ascending order
        boolean isSorted = true;

        for (int i = 1; i < numbersList.size(); i++) {

            if (numbersList.get(i) <
                numbersList.get(i - 1)) {

                isSorted = false;
                break;
            }
        }

        System.out.println(
                "Sorted ascending: " + isSorted);
    }
}

Alternative

Create a copy of the list.

Use:

Collections.sort()

Then compare the sorted copy with the original list.


FAQs

Which collections do you use in an automation project?

  • ArrayList (web elements and test data)

  • HashMap (property file key-value data)

  • HashSet (unique values and window handles)

  • List (findElements() returns List<WebElement>)

  • Map


How do you make a class immutable?

  • Declare the class as final.

  • Make fields private final.

  • Don't provide setters.

  • Use a parameterized constructor.

  • Deep copy mutable fields.

  • Return copies from getter methods.


What is the difference between final, finally, and finalize?

  • final makes variables, methods, or classes unchangeable.

  • finally executes regardless of whether an exception occurs.

  • finalize is a cleanup method invoked by the Garbage Collector.


What is the difference between an abstract class and an interface?

An abstract class can contain both abstract and concrete methods and different variable types.

An interface primarily defines a contract, supports multiple inheritance, and contains static and final variables.


Is multiple inheritance possible in Java?

No.

Java does not support multiple inheritance of classes because of the Diamond Problem.

However, a class can implement multiple interfaces.


Where does method overloading appear in Selenium?

  • Utility methods such as overloaded enterText()

  • Selenium APIs like:

    • switchTo().frame(int)

    • switchTo().frame(String)

    • switchTo().frame(WebElement)


How do you compare strings in Selenium tests?

Use:

  • equals() for conditional logic.

  • Assert.assertEquals() for test validation.

Never use == to compare string content.


How do you verify that a list is sorted?

Retrieve the values, convert them into a List<Integer>, and verify each element is greater than or equal to the previous one.

Alternatively, compare the original list with a sorted copy.