0

I don't know how do I tackle this compilation error.

my code is

public ArrayList<Student> SortOnCGPA(ArrayList<Student> stu){        
        Student sorStu[] = stu.toArray();
        Arrays.sort(sorStu, new StuDescend());
        stu = new ArrayList(Arrays.asList(sorStu));
        return stu;
    }

and the error is:

JavaPQ.java:23: error: incompatible types: Object[] cannot be converted to Student[]
        Student sorStu[] = stu.toArray();
                                      ^
Note: JavaPQ.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error

I know that the "toArray()" method will return an array of type Object. I don't know how to typecast it to Student[] or any alternative solution. Thanks for for your help.

I used a loop to solve my problem

public ArrayList<Student> SortOnCGPA(ArrayList<Student> stu){        
        Student sorStu[] =new Student[stu.size()];
        Iterator it = stu.iterator();
        int i = 0;
        while(it.hasNext()){
            sorStu[i] = new Student((Student)it.next());
            i++;
        }
        Arrays.sort(sorStu, new StuDescend());
        stu = new ArrayList(Arrays.asList(sorStu));
        return stu;
    }

But I wanted to know how do I use the ".toArray()" method of the collections framework.

vivek gupta
  • 103
  • 1
  • 12

0 Answers0