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


Java java.util.Collections.sort()用法及代碼示例


描述

這個sort(List<T>)方法用於將指定列表按照其元素的自然順序進行升序排序。

聲明

以下是聲明java.util.Collections.sort()方法。

public static <T extends Comparable<? super T>> void sort(List<T> list)

參數

list- 這是要排序的列表。

返回值

NA

異常

  • ClassCastException- 如果列表包含不可相互比較的元素(例如,字符串和整數),則拋出。

  • UnsupportedOperationException− 如果指定列表的 list-iterator 不支持設置操作,則拋出。

示例

下麵的例子展示了 java.util.Collections.sort() 的用法

package com.tutorialspoint;

import java.util.*;

public class CollectionsDemo {
   public static void main(String args[]) {

      // create an array of string objs
      String init[] = { "One", "Two", "Three", "One", "Two", "Three" };

      // create one list
      List list = new ArrayList(Arrays.asList(init));

      System.out.println("List value before:"+list);

      // sort the list
      Collections.sort(list);

      System.out.println("List value after sort:"+list);
   }
}

讓我們編譯並運行上麵的程序,這將產生以下結果。

List value before:[One, Two, Three, One, Two, Three]
List value after sort:[One, One, Three, Three, Two, Two]

相關用法


注:本文由純淨天空篩選整理自 java.util.Collections.sort() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。