Hi all,
I've been trying to do this for a few hours now, I've seen several suggestions that
castin the toArray() method to a (String[]) should work but this results in runtime errors for me. Code is below, any help would be appreciated.
Error is with the getStudents() method, there may be other errors but that's the one I'm concentrating on at the moment.
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
at Course.getStudents(Exercise10_09.java:61)
at Exercise10_09.main(Exercise10_09.java:19)
I figured this shouldn't work as casting can only promote types? Correct me if I'm wrong.
import java.util.ArrayList;
public class Exercise10_09
{
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());
course1.dropStudent("Brian Smith");
System.out.println("Number of students in course1: "
+ course1.getNumberOfStudents());
students = course1.getStudents();
for (int i = 0; i < course1.getNumberOfStudents(); i++)
System.out.print(students[i] + ", ");
}
}
class Course
{
private String courseName;
private String instructor;
private ArrayList students = new ArrayList();
public Course(String courseName)
{
this.courseName = courseName;
}
public Course(String courseName, String instructor)
{
this.courseName = courseName;
this.instructor = instructor;
}
public void addStudent(String student)
{
students.add(student);
}
public String[] getStudents()
{
students.trimToSize();
String[] studenta = (String[])students.toArray();
return studenta;
}
public int getNumberOfStudents()
{
students.trimToSize();
return students.size();
}
public String getCourseName()
{
return courseName;
}
public void dropStudent(String student)
{
students.remove(student);
}
public void clear()
{
students.clear();
}
}