Itheyln
Itheyln

Reputation: 121

Sorting a LinkedList of objects with Collections.sort

Okay so my LinkedList contains objects of the Student Class:

public class Student implements Comparable<Student>, Serializable {
    private String name;
    private String gNumber;
    private double gpa;



    public int compareTo(Student s) {
        return name.compareTo(s.getName());
    }

And i am attempting to use Collections.sort to sort my LinkedList:

public class SimpleDatabase implements iSimpleDatabase {
     LinkedList<Student> list = new LinkedList<Student>();
     //code

    @Override
    public void Sort() {
        Collections.sort((List<Student>) list);

    }

the sort method would be called from my GUI actionlistener, however when I attempt to sort it i get the error:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException:   package1.LinkedList cannot be cast to java.util.List

On the line that calls the Collections.sort().

I'm sure I'm just being really stupid and all, but I can' for the life of me figure this out and I can't find anything online that explains why it isn't working for me. Thanks for any help.

Upvotes: 0

Views: 1262

Answers (2)

Simba
Simba

Reputation: 1651

To use Collections.sort you should have your LinkedList class implement java.util.List,

You can also use the LinkedList implementation from the standard library:

See here

Upvotes: 0

Rogue
Rogue

Reputation: 11483

You've defined your own "LinkedList" class in package1.LinkedList, which is what you're attempting to pass to Collections#sort. Your custom class either needs to implement the List interface or you should use java.util.LinkedList

Upvotes: 6

Related Questions