Java教程

Java Vector sort()

Java Vector类的 sort()方法用于根据由Java引发的顺序对向量进行排序。

语法

下面是 sort()方法的声明:
Public void sort(Comparator<? super E> c)

参数

参数 说明 必需/可选
c 比较器,用于比较向量元素。 必需

返回

此方法的返回类型为 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

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4