Java Vector 類的 sort() 方法用於根據指定的 Comparator 引入的順序對向量進行排序。
用法
以下是 sort() 方法的聲明:
Public void sort(Comparator<? super E> c)
參數
參數 | 描述 | 必需/可選 |
---|---|---|
c | 它是用於比較向量元素的比較器。 | Required |
返回
此方法的返回類型為 void,因此它不返回任何內容。
異常
NA
兼容版本
Java 1.2 及以上
例子1
import java.util.*;
public class VectorSortExample1 {
public static void main(String arg[]) {
//Create an empty vector
Vector<Integer> vec = new Vector<>();
//Add elements in the vector
vec.add(1);
vec.add(5);
vec.add(2);
vec.add(4);
vec.add(3);
//Display the vector elements
System.out.println("Components of the vector:"+vec);
//Sorting the vector
Collections.sort(vec);
//Displaying the vector elements after sort() method
System.out.println("Components of the vector after sorting:"+vec);
}
}
輸出:
Components of the vector:[1, 5, 2, 4, 3] Components of the vector after sorting:[1, 2, 3, 4, 5]
例子2
import java.util.*;
public class VectorSortExample2 {
public static void main(String arg[]) {
//Create an empty vector
Vector < String > vec = new Vector < String > ();
//Add elements in the vector
vec.add("White");
vec.add("Green");
vec.add("Black");
vec.add("Orange");
System.out.println("The vector elements are:");
//Display the vector elements
for (String colors:vec) {
System.out.println(" "+colors);
}
//Sorting the vector
Collections.sort(vec);
//Displaying the vector elements after sort() method
System.out.println("The vector elements after sort() method are:");
for (String colors:vec) {
System.out.println(" "+colors);
}
}
}
輸出:
The vector elements are: White Green Black Orange The vector elements after sort() method are: Black Green Orange White
相關用法
- Java Vector set()用法及代碼示例
- Java Vector subList()用法及代碼示例
- Java Vector setSize()用法及代碼示例
- Java Vector setElementAt()用法及代碼示例
- Java Vector size()用法及代碼示例
- Java Vector spliterator()用法及代碼示例
- Java Vector removeIf()用法及代碼示例
- Java Vector toArray()用法及代碼示例
- Java Vector addAll()用法及代碼示例
- Java Vector listIterator()用法及代碼示例
- Java Vector addElement()用法及代碼示例
- Java Vector removeRange()用法及代碼示例
- Java Vector clone()用法及代碼示例
- Java Vector ensureCapacity()用法及代碼示例
- Java Vector trimToSize()用法及代碼示例
- Java Vector replaceAll()用法及代碼示例
- Java Vector iterator()用法及代碼示例
- Java Vector firstElement()用法及代碼示例
- Java Vector insertElementAt()用法及代碼示例
- Java Vector toString()用法及代碼示例
注:本文由純淨天空篩選整理自 Java Vector sort() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。