-1

I am trying to write a generic class definition for class UniCourse that stores students that are registered in the course.

It creates UniCourse objects that use student emails as identities (e.g. abc123 :: (Type String), or student Id :: (Type Integer).

I'm getting this warning:

unchecked cast required: T[] found: java.lang.Object[]

Could someone explain what this means and how to fix this?

public class UniCourse<T> {
    private T[] students;

    public UniCourse (int size) {
    T[] students = (T[]) new Object[size];
  }
}
help-info.de
  • 6,695
  • 16
  • 39
  • 41
user12099607
  • 11
  • 1
  • 4

1 Answers1

0

One Solution would be to create your own Student Class which holds an array of your data as an Object. Your Student Class could look like this:

public class Student<T> {
    protected Object[] data;

    public Student (int size) {
    this.data = new Object[size];
  }
}

Then in your UniCourse Class you could create a Constructor like this:

public UniCourse(int size) {
  this.students = new Student<T>(size);
}

And finally you can call your Constructor with this line:

UniCourse<Integer> uniCourse = new UniCourse<Integer>(20);

To access the data Array created in your Student class you can simply do something like this:

this.students.data;
Paku580
  • 116
  • 5