繁体   English   中英

ArrayList 与抽象 class

[英]ArrayList with abstract class

我想将员工插入该系统并检索 ArrayList 内部的内容,但它每次都给我一个“Null”。 请注意,它是抽象员工 class。

        public static void main(String[] args) {
            ArrayList<Employee> AllEmployees = new ArrayList();

这里我添加 Employee 类型的 ArrayList

            Employee CE = new CommissionEmployee();
            HourlyEmployee HE = new HourlyEmployee();
    

在这里,我创建了 super Employee 的子类

            Scanner input = new Scanner(System.in);
            int count = 0;
            int choice;
            do {
                System.out.println("Choose 1 to insert a new employee to the company.");
                System.out.println("Choose 2 to add a new product for a Commission Employee.");
                System.out.println("Choose 3 to add the overtime hours for an Hourly Employee.");
                System.out.println("Choose 4 to remove an employee from the company.");
                System.out.println("Choose 5 to sort the employees in the company based on their names.");
                System.out.println("Choose 0 to exit.");
                System.out.println("Enter your choice");
                choice = input.nextInt();
    
                switch (choice) {
                    case 1: {
                        System.out.println("Please enter the first name:");
                        String FName = input.next();
                        System.out.println("Please enter family name:");
                        String LName = input.next();
                        String Name = FName + " " + LName;
                        System.out.println("Please enter the job description for this employee S/ s for Salesman, N/ n for Network Administrator, D/ d for Developer, or Q/ q for Quality Assurance:");
                        String Job = input.next();
    
                        AllEmployees.add(HE.create(Name, Job));

我不知道我所做的是否正确我尝试将新员工添加到 ArrayList。

                        Iterator<Employee> it = AllEmployees.iterator();
                        System.out.println("Commission Employees are:");
                        for (int i = count; i >= 0; i--) {
    
                            System.out.println(it.next());
                        }
                        count++;

在这里,我想打印列表中的所有员工。

                    }
    
                    case 2:
                    case 3:
                    case 4:
                    case 5:
    
                }
            } while (choice != 0);
        }
    
    }

您的代码还有许多其他问题,但只关注您的null问题,它必须位于这一行:

 AllEmployees.add(HE.create(Name, Job));

function 的返回值将被添加到列表中。 所以我怀疑你的HE.create(Name, Job) function 返回null ,这个值将被添加到ArrayList实例中。 如果您通常无法成功添加到列表中,那么迭代器不会向您提供null值,而是会抛出异常,或者什么也不做,如果您安全地迭代它。

你没有。 当使用迭代器从列表中获取值时,我强烈建议根据检查它是否有更多值( Iterator.hasNext() )进行迭代,或者至少根据列表中元素的数量( List.size() )。 现在,如果您过于频繁地尝试访问it.next() ,您的代码很容易触发NoSuchElementException

暂无
暂无

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

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