我有一个String []到arraylist家庭作业

时间:2015-10-11 23:37:45

标签: java arrays arraylist

这是我写的代码:

public class TestCourse {   public static void main(String[] args) {
    Course course1 = new Course("Data Structures");
    Course course2 = new Course("Database Systems");

    course1.addStudent("Peter Jones");
    course1.addStudent("Brian Smith");
    course1.addStudent("Anne Kennedy");

    course2.addStudent("Peter Jones");
    course2.addStudent("Steve Smith");

    System.out.println("Number of students in course1: "
      + course1.getNumberOfStudents());
    String[] students = course1.getStudents();
    for (int i = 0; i < course1.getNumberOfStudents(); i++)
      System.out.print(students[i] + ", ");

    System.out.println();
    System.out.print("Number of students in course2: "
      + course2.getNumberOfStudents());   } }

import java.util.ArrayList; public class Course {

    private String courseName;
    private ArrayList<String> students = new ArrayList<>();
    private int numberOfStudents;

    public Course(String courseName) {
        this.courseName = courseName;
    }
    public void addStudent(String name) {
        students.add(name);
        numberOfStudents ++;
    }
    public ArrayList getStudents() {
        return students;
    }
    public int getNumberOfStudents() {
        return numberOfStudents;
    }

    public String getCourseName() {
        return courseName;
    }
    public void dropStudents(ArrayList students) {
        this.students = students;
        students.remove(students);
        numberOfStudents --;
    } }

我有错误 String[] students = course1.getStudents();在测试课程中。

我试图加入arraylist,但它没有工作......

1 个答案:

答案 0 :(得分:0)

首先,您返回raw type。所以修复它。像,

public ArrayList<String> getStudents() {
    return students;
}

接下来,您可以调用List.toArray(T[])之类的

String[] students = course1.getStudents().toArray(new String[]{});

直接使用List,例如

List<String> students = course1.getStudents();
for (String student : students) {
    // Do something with each student.
}