1. 程式人生 > >【我的Java筆記】集合工具類_Collections

【我的Java筆記】集合工具類_Collections

Collections類

1.概述:針對Collection集合操作的工具類 2.常用方法: (1)public static <T> void sort(List<T> list)排序,預設按照自然順序
(2)public static <T> int binarySearch(List<?> list,T key)二分查詢
(3)public static <T> T max(Collection<?> coll)獲取最大值
(4)public static void reverse(List<?> list)反轉
(5)
public static void shuffle(List<?> list)隨機置換
例:
import java.util.ArrayList;
import java.util.Collections;

public class CollectionsDemo {
	public static void main(String[] args) {
		ArrayList<Integer> al = new ArrayList<Integer>();
		al.add(7);
		al.add(31);
		al.add(9);
		al.add(45);
		al.add(96);
		al.add(33);

		// public static <T> void sort(List<T> list) 排序,預設按照自然順序
		Collections.sort(al);
		System.out.println("sort:" + al);

		System.out.println("---------------------------");

		// public static <T> int binarySearch(List<?> list,T key): 二分查詢 (前提元素必須有序)
		int index = Collections.binarySearch(al, 33);
		System.out.println("binarySearch:" + index);

		System.out.println("---------------------------");

		// public static <T> T max(Collection<?> coll): 獲取最大值
		int max = Collections.max(al);
		System.out.println("max:" + max);

		System.out.println("---------------------------");

		// public static void reverse(List<?> list): 反轉集合
		Collections.reverse(al);
		System.out.println("reverse:" + al);

		System.out.println("---------------------------");
		// public static void shuffle(List<?> list): 隨機置換
		Collections.shuffle(al);
		System.out.println("shuffle:" + al);

	}
}