Monday, December 30, 2024
Google search engine
HomeLanguagesJavaCan an ArrayList Contain Multiple References to the Same Object in Java?

Can an ArrayList Contain Multiple References to the Same Object in Java?

ArrayList class in Java is basically a resizable array i.e. it can grow and shrink in size dynamically according to the values that we add or remove to/from it. It is present in java.util package.

We will discuss if an ArrayList can contain multiple references to the same object in Java.

The ArrayList in java does not provide the checks for duplicate references to the same object. Therefore, we can insert the same object or reference to a single object as many times as we want. If we wish we can check if an element already exists in ArrayList or not with the help of the contains() method. 

Below is the code implementation of the above problem statement:

Java




// Java program to demonstrate some functionalities
// of ArrayList
 
import java.util.ArrayList;
 
class Employee{
    private String name;
    private String designation;
 
    // Parameterized constructor for Employee class
    public Employee(String name, String designation) {
        this.name = name;
        this.designation = designation;
    }
 
    // Creating getters for Employee class
    public String getName() {
        return name;
    }
 
    public String getDesignation() {
        return designation;
    }
}
 
public class GFG {
    public static void main(String[] args) {
 
        // Creating Objects of Employee class
        Employee e1 = new Employee("Raj","Manager");
        Employee e2 = new Employee("Simran", "CEO");
        Employee e3 = new Employee("Anish", "CTO");
 
        // Creating an ArrayList of Employee type
        ArrayList<Employee> employeeList= new ArrayList<>();
 
        // Inserting the employee objects in the ArrayList
        employeeList.add(e1);
        employeeList.add(e2);
        employeeList.add(e3);
 
        // e1 will be inserted again as ArrayList can store multiple
        // reference to the same object
        employeeList.add(e1);
 
        // Checking if e2 already exists inside ArrayList
        // if it exists then we don't insert it again
        if(!employeeList.contains(e2))
            employeeList.add(e2);
 
        // ArrayList after insertions: [e1, e2, e3, e1]
 
        // Iterating the ArrayList with the help of Enhanced for loop
        for(Employee employee: employeeList){
            System.out.println(employee.getName() + " is a " + employee.getDesignation());
        }
    }
}


Output

Raj is a Manager
Simran is a CEO
Anish is a CTO
Raj is a Manager
RELATED ARTICLES

Most Popular

Recent Comments