Java中的ArrayList能否包含对同一个对象的多个引用?
Java中的ArrayList类基本上是一个可调整大小的数组,即它可以根据我们添加或删除的值在大小上动态增加和缩小。它是在java.util包中定义的。
我们将讨论Java中ArrayList是否可以包含对同一个对象的多个引用。
Java中的ArrayList不提供对相同对象的重复引用的检查。因此,我们可以将相同对象或对单个对象的引用插入多次。如果需要,我们可以使用contains()方法检查ArrayList中是否已存在元素。
以下是上述问题陈述的代码实现:
// Java程序演示ArrayList的一些功能
//
import java.util.ArrayList;
class Employee{
private String name;
private String designation;
// Employee类的参数构造函数
public Employee(String name, String designation) {
this.name = name;
this.designation = designation;
}
// 为Employee类创建getter函数
public String getName() {
return name;
}
public String getDesignation() {
return designation;
}
}
public class GFG {
public static void main(String[] args) {
// 创建Employee类的对象
Employee e1 = new Employee("Raj","Manager");
Employee e2 = new Employee("Simran", "CEO");
Employee e3 = new Employee("Anish", "CTO");
// 创建Employee类型的ArrayList
ArrayList<Employee> employeeList= new ArrayList<>();
// 将employee对象插入ArrayList
employeeList.add(e1);
employeeList.add(e2);
employeeList.add(e3);
// 由于ArrayList可以存储同一个对象的多个引用,
// 因此e1将再次被插入
employeeList.add(e1);
// 检查e2是否已存在于ArrayList中,
// 如果存在,则不重复插入
if(!employeeList.contains(e2))
employeeList.add(e2);
// ArrayList插入后的结果:[e1, e2, e3, e1]
// 使用增强for循环遍历ArrayList
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
极客教程