简体   繁体   中英

how to access arraylist of another class

Suppose I have a class manager which stores Arraylist of class Employee say:

class Manager {

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

Now is it possible to get the name of Manager object by some method in Employee class? In other words, finding the name of Arraylist using element.

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.

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. 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;
                }
          }
       }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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