Dynamically fill in an ArrayList with objects

前端 未结 1 1040
滥情空心
滥情空心 2021-01-23 05:44

I have the abstract class Human, which is extendet by other two classes Student and Worker. I`m am trying to fill in two array lists. ArrayList of type Student and ArrayList of

1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-23 06:19

    Sure, just add the students:

    ArrayList students = new ArrayList<>(); // note: students
    students.add(new Student("Jens", "Nenov", "A+"));
    

    You can do almost exactly the same thing for the workers. If you want to use a loop, do the following:

    for (int i=0; i<50; i++) {
        students.add(new Student("Jens"+i, "Nenov", "A+"));
    }
    

    This will create a list of new students with different numbers after their names. If you want different data, though, that data needs to come from somewhere. For example, you might get the data from user input:

    Scanner input = new Scanner(System.in);
    for ...
        System.out.println("Enter a first name:");
        String firstname = input.nextLine();
        ...
        students.add(new Student(firstname, lastname, grade));
    

    0 讨论(0)
提交回复
热议问题