简体   繁体   English

当 ArrayList 和构造函数/getter 存储另外两个类时,如何从一个类添加到 ArrayList

[英]How do I add to an ArrayList from one class, when the ArrayList and constructors/getters are stored 2 other classes

I have 3 classes, Session , Employee , and Employees .我有 3 个类, SessionEmployeeEmployees The Employee class has the constructors and getters, the Employees class has the ArrayList , and I'm trying to add to that ArrayList within the Session class. Employee类有构造函数和 getter, Employees类有ArrayList ,我试图在Session类中添加到该ArrayList

public class Employee {
    public Employee(String name, String email){
        this.name = name;
        this.email = email;
    }

    public String getName(){
        return name;
    }

    public String getEmail(){
        return email;
    }
}
public class Employees {
    private ArrayList<Employee> employees = new ArrayList<Employee>();

    public Employees(){
        employees.add(new Employee("John Smith", "johnsmith@email.com"));
    }

    public void addEmpNew (Employee empNew){
        employees.add(empNew);
    }
}
public class Session {
    private void addEmployee(){
        System.out.print("Name: ");
        String addEmpName = In.nextLine();

        System.out.print("Email: ");
        String addEmpEmail = In.nextLine();

        Employees v1 = new Employees();
        v1.addEmpNew(new Employee(addEmpName, addEmpEmail));
    }
}

But when I run it and put in the new employee and use a viewEmployees() method that shows all employees, It doesn't show the new one I added in, only showing the john smith one I pre-wrote in. I have a suspicion there may be something wrong with the addEmpNew method but I'm not sure.但是当我运行它并放入新员工并使用显示所有员工的viewEmployees()方法时,它没有显示我添加的新员工,只显示我预先写入的约翰史密斯。我有一个怀疑addEmpNew方法可能有问题,但我不确定。

You are creating an instance of Employees (called v1) within the addEmployee method.您正在addEmployee方法中创建一个Employees 实例(称为v1)。 After the addEmployee method completes, all of the variables inside the method are gone (ready to be garbage collected). addEmployee方法完成后,该方法中的所有变量都消失了(准备好进行垃圾回收)。

If you are expecting to only have one instance of the Employees, consider making it a global variable.如果您希望只有一个 Employees 实例,请考虑将其设为全局变量。

public class Session {
    private final Employees v1 = new Employees();

    private void addEmployee(){
        System.out.print("Name: ");
        String addEmpName = In.nextLine();

        System.out.print("Email: ");
        String addEmpEmail = In.nextLine();

        v1.addEmpNew(new Employee(addEmpName, addEmpEmail));
    }

    private void printEmployees(){
        // you will have to implement the toString method in Employees class
        System.out.print("Employees: " + v1.toString());
    }
}

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

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