Java Collections.sort Vector

How do I use compareTo method in my class to sort a vector of objects of that class

for example in the main method I would have something like:

Vector myVector  = new Vector();

Vector.add(new MyClass(1) );
...

Collections.sort(myVector);


I've tried a few things but I keep getting this error:


Exception in thread "main" java.lang.ClassCastException: MyClass
      at java.util.Arrays.mergeSort(Unknown Source)
      at java.util.Arrays.mergeSort(Unknown Source)
      at java.util.Arrays.sort(Unknown Source)
      at java.util.Collections.sort(Unknown Source)
polkadotAsked:
Who is Participating?
 
runa_paathakCommented:
Collections.sort(myVector);

sorts myVector "into ascending order, according to the natural ordering of its elements". JavaDocs add "All elements in the list must implement the Comparable interface. Furthermore, all elements in the list must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the list)."

So you must
1. have your class MyClass implement the Comparable interface
2. Make sure myVector contains only objects of type MyClass.
0
 
CEHJCommented:
Your classes need to be Comparable or you need to use a custom Comparator
0
 
objectsCommented:
0
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

 
Mayank SAssociate Director - Product EngineeringCommented:
0
 
maclemaCommented:
try this: I am using getEmployeeID as an example. you can use whatever method you choose to do the comparison

        public static Comparator CMP_MyClass = new Comparator<MyClass>()
      {
            public int compare(MyClassobjA, MyClassobjB)
            {
                final int BEFORE = -1;
                final int AFTER = 1;
                  final int EQUAL = 0;
               
                if ( objA.getEmployeeID() < objB.getEmployeeID() )
                {
                  return BEFORE;
                }
                else if ( objA.getEmployeeID() == objB.getEmployeeID() )
                {
                  return EQUAL;
                }
                else
                {
                  return AFTER;
                }
            }
      };

Collections.sort(myVector, CMP_MyClass);
0
 
CEHJCommented:
:-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.