使用arraylist创建输入

时间:2018-01-11 21:48:21

标签: java arraylist

我想我已经陷入了混乱。我在下面的两个addMember部分有老师和学生。出于我正在做的目的,他们必须在一个部分,但当有人想要添加学生或教师时,他们需要能够单独添加(所以一个电话可以选择添加)。但是我对arrayLists的了解并不是很好,因为你可以看到它并不是很好。任何帮助都非常需要和赞赏。

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;



public class Committee {

    private String name;

    private List<Object> members;

    public Committee(String name) 
    {
        this.name = name;
        members = new ArrayList<Object>();
        List list = new ArrayList();
    }

    public void addMember(Student student, Teacher teacher) 
    {
        List members1 = new ArrayList();
        members1.add(student);
        System.out.println(members1);
        List members2 = new ArrayList();
        members2.add(teacher);
        System.out.println(members2);
    }

    public void printMembership() 
    {
        System.out.println("Membership of the " + name + " Committee ");
        Iterator<Object> it = members.iterator();
        while (it.hasNext()) 
        {
            Object member = it.next();
            System.out.println(members);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我不确定你想要达到什么目标,所以我会写两个解决方案:

  1. 您希望拥有一个列表的情况

    interface Member {...}
    class Student implements Member {...}
    class Teacher implements Member {...}
    
    public class Comittee {
        private list<Member> members;
    
        public void addMember(Member member) {
            members.add(member);
        }
    
        public void printMembership() {
            members.forEach(System.out::println);
        }
    } 
    
  2. 您希望拥有两个列表的情况

    interface Member ...
    class Student implements Member ...
    class Teacher implements Member ...
    
    public class Comittee {
        private list<Teacher> teachers;
        private list<Student> students;
    
        public void addMember(Student student, Teacher teacher) {
            students.add(student);
            teachers.add(teacher);
        }
    
        public void printMembership() {
            getAllMembers().forEach(System.out::println);
        }
    
        private void getAllMembers(): List<Member> {
            List<Member> allMembers = ArrayList<>(students.size() + teachers.size());
            allMembers.addAll(teachers);
            allMembers.addAll(students);
            return allMembers;
        }
    }