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
import java.util.ArrayList;
class Employee{
private String name;
private String designation;
public Employee(String name, String designation) {
this .name = name;
this .designation = designation;
}
public String getName() {
return name;
}
public String getDesignation() {
return designation;
}
}
public class GFG {
public static void main(String[] args) {
Employee e1 = new Employee( "Raj" , "Manager" );
Employee e2 = new Employee( "Simran" , "CEO" );
Employee e3 = new Employee( "Anish" , "CTO" );
ArrayList<Employee> employeeList= new ArrayList<>();
employeeList.add(e1);
employeeList.add(e2);
employeeList.add(e3);
employeeList.add(e1);
if (!employeeList.contains(e2))
employeeList.add(e2);
for (Employee employee: employeeList){
System.out.println(employee.getName() + " is a " + employee.getDesignation());
}
}
}
|
OutputRaj is a Manager
Simran is a CEO
Anish is a CTO
Raj is a Manager