當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Vector sort()用法及代碼示例


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 sort() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。