简体   繁体   English

如何访问另一个类的arraylist

[英]how to access arraylist of another class

Suppose I have a class manager which stores Arraylist of class Employee say:假设我有一个存储类 Employee 的 Arraylist 的类管理器说:

class Manager {

    ArrayList<Employee> x = new ArrayList<>();
}

Now is it possible to get the name of Manager object by some method in Employee class?现在是否可以通过 Employee 类中的某种方法获取 Manager 对象的名称? In other words, finding the name of Arraylist using element.换句话说,使用元素查找 Arraylist 的名称。

If you want to get the manager object from employee object then you have to implement bi directional mapping.如果您想从员工对象中获取经理对象,那么您必须实现双向映射。 Add manager attribute in employee class as well.在员工类中也添加经理属性。

The problem as I understand, is to find the manager of a given employee.据我了解,问题是找到给定员工的经理。 To do this you'll need a list of all managers and the details of the employee you search the manager for.为此,您需要一份所有经理的列表以及您搜索经理的员工的详细信息。

class Manager
    {
       private String name;
       private List<Employee> employees;

       public List<Employee> getEmployees()
       {
         return this.employees;
       }

       public String getName()
       {
          return this.name;
       }
    }

If you are using existing object of an Employee (You get the Employee object out of a list of employees in a Manager object), following approach will work.如果您使用的是 Employee 的现有对象(您从 Manager 对象中的员工列表中获取 Employee 对象),则以下方法将起作用。

class FunctionClass{
   public static void main(String[] args)
   {
      List<Manager> allManagers = getAllManagers();
      Employee currEmployee = getCurrentEmployee();

      for( Manager manager : allManagers )
      {
         if( manager.getEmployees().contains( currEmployee ) )
         {
            System.out.println( manager.getName() );
            break;
         }
      }
   }
}

If you are creating objects of Employee from provided data, above approach will not work.如果您从提供的数据创建 Employee 对象,则上述方法将不起作用。 You will have to iterate through all the employees of each manager.您必须遍历每个经理的所有员工。

class FunctionClass{
       public static void main(String[] args)
       {
          List<Manager> allManagers = getAllManagers();
          Employee currEmployee = getCurrentEmployee();

          for( Manager manager : allManagers )
          {
             for( Employee emp: manager.getEmployees() )
             {
                if( /*compare if emp and currEmployee equal*/ )
                {
                  System.out.println( manager.getName() );
                  break;
                }
          }
       }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM