What is the method for sorting vectors in Java?
There are two ways to sort a Vector in Java.
- By using the sort() method of the Collections class, you can sort a Vector by calling the static sort() method of the Collections class. The sort() method will automatically sort the Vector according to the natural order of its elements.
import java.util.Collections;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Vector<Integer> vector = new Vector<>();
vector.add(5);
vector.add(2);
vector.add(7);
vector.add(1);
vector.add(3);
Collections.sort(vector);
System.out.println(vector);
}
}
The output is: [1, 2, 3, 5, 7]
- One option:
You can create a custom implementation of the Comparator interface to sort a Vector. The Comparator interface has a compare() method that allows you to define your own sorting rules.
import java.util.Comparator;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Vector<Integer> vector = new Vector<>();
vector.add(5);
vector.add(2);
vector.add(7);
vector.add(1);
vector.add(3);
vector.sort(new MyComparator());
System.out.println(vector);
}
}
class MyComparator implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2; // 自定义排序规则
}
}
The output displays: [1, 2, 3, 5, 7]