Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What function can be used to sort a Vector?

Tags:

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);
like image 881
Hidayat Avatar asked Jan 15 '10 14:01

Hidayat


People also ask

Which function is used for sorting in R?

There is a function in R that you can use (called the sort function) to sort your data in either ascending or descending order. The variable by which sort you can be a numeric, string or factor variable.

How do I sort a vector in R?

To sort a vector in R programming, call sort() function and pass the vector as argument to this function. sort() function returns the sorted vector in increasing order. The default sorting order is increasing order. We may sort in decreasing order using rev() function on the output returned by sort().

How do you sort a vector without using the sort function?

The vector can use the array notation to access the elements. If you don't want to use the default std::sort , or std::sort with custom comparator, you can use qsort or write your own.

How does vector sort work in C++?

It will return the iterator to the beginning of arrays. It will return the constant iterator to the beginning. It will return a reverse iterator to the reverse beginning of arrays.


2 Answers

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.

like image 109
BalusC Avatar answered Oct 17 '22 00:10

BalusC


Vector implements List, so Collections.sort would work.

like image 37
jsight Avatar answered Oct 17 '22 01:10

jsight