ArrayList 可以包含对Java中同一对象的多个引用吗?
Java中的 ArrayList 类基本上是一个可调整大小的数组,即它可以根据我们向其中添加或从中删除的值动态地增长和缩小大小。它存在于Java.util 包中。
我们将讨论 ArrayList 是否可以包含对Java中同一对象的多个引用。
Java中的 ArrayList 不提供对同一对象的重复引用的检查。因此,我们可以根据需要多次插入相同的对象或对单个对象的引用。如果我们愿意,可以借助 contains() 方法检查元素是否已存在于 ArrayList 中。
下面是上述问题陈述的代码实现:
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 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());
}
}
}
输出
Raj is a Manager
Simran is a CEO
Anish is a CTO
Raj is a Manager