Java 数组列表能否包含对同一对象的多个引用

Java 数组列表能否包含对同一对象的多个引用

Java中的ArrayList类基本上是一个可调整大小的数组,也就是说,它可以根据我们添加或删除的值动态地增长和缩小。它存在于java.util包中。

我们将讨论在Java中ArrayList是否可以包含对同一对象的多个引用。

java中的ArrayList不提供对同一对象重复引用的检查。因此,我们可以随心所欲地插入同一个对象或对一个对象的引用。如果我们愿意,我们可以借助contains()方法来检查一个元素是否已经存在于ArrayList中。

下面是上述问题陈述的代码实现。

// 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());
        }
    }
}
Java

输出

Raj is a Manager
Simran is a CEO
Anish is a CTO
Raj is a Manager
Java

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册