I cant find any sorting function in the java API for vectors.
Collections.sort
is only for List<T>
and not for Vector<T>
.
I don't want to write my own sorting function because I think java should implement this.
I'm looking for something like:
class ClassName implements Comparator<ClassName> ..
ClassName cn = ..;
sort(cn);
As per the API docs, Vector
just implements List
, so I don't forsee problems. Maybe your confusion was caused because you declared Vector
according the old Java 1.0 style:
Vector vector = new Vector();
instead of the declaring it aginst the interface (which is considered good practice):
List list = new Vector();
You can thus just make use of Collections#sort()
to sort a collection, Comparable
to define the default ordering behaviour and/or Comparator
to define an external controllable ordering behaviour.
Here's a Sun tutorial about ordering objects.
Here's another SO answer with complete code examples.
That said, why are you still sticking to the legacy Vector
class? If you can, just replace by the improved ArrayList
which was been designed as replacement of Vector
more than a decade ago.
Vector implements List, so Collections.sort would work.
According to the Java API Specification for the Vector
class, it implements the List
interface which is needed to use the Collections.sort
method.
Also, as a note, for most uses the Vector
class could be replaced by using one of the List
implementations in the Java Collections Framework, such as ArrayList
. The Vector
class is synchronized, so unless there is a real need for synchronized access one should use one of the other List
implementations.
Collections.sort(nameOfTheVectorToBeSorted); try this on your vector, that will get sorted.
Don't forget to add implements Comparable<>
in your class:
public class XXXX
implements Comparable<XXXX> {
}
And to redefine compareTo()
in your class of the object type stored in your vector.
I got this problem as well, Eclipse IDE was telling me that Collection.sort()
was for List<T>
only. Couldn't make it work until I did what I just said.
Collections.sort(vector_name)
It'll sort the vector in place, so you don't need to assign the result of the above command back to the vector.
This works because Vectors are implementations of Lists.