Collections是一个非常实用的工具类,这里了解一下官网api里的方法
sort 实现对List类型的排序操作
1 | public static <T> void sort(List<T> list, Comparator<? super T> c) |
参数
- list - 要排序的list
- c - 可选 比较器,可以自定义比较方法
例子
1 | Collections.sort(list, new Comparator<Point>(){ |
binarySearch 二分查找
1 | public static <T> int binarySearch(List<? extends T> list, |
参数
- list - the list to be searched.
- key - the key to be searched for.
- c - the comparator by which the list is ordered. A null value indicates that the elements’ natural ordering should be used.
返回
如果找到,返回从0开始的下标>=0,否则返回 -(insertion point)-1
reverse 翻转list
1 | public static void reverse(List<?> list) |
shuffle
1 | public static void shuffle(List<?> list, Random rnd)) |
swap 交换下标对应元素
1 | public static void swap(List<?> list, int i, int j) |
fill 把list全部修改成同一个值
1 | public static <T> void fill(List<? super T> list,T obj) |
copy
1 | public static <T> void copy(List<? super T> dest, List<? extends T> src) |
min&max
1 | public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll) |
rotate
1 | public static void rotate(List<?> list, int distance) |
replaceAll
1 | public static <T> boolean replaceAll(List<T> list, |
indexOfSubList lastIndexOfSubList
1 | public static int indexOfSubList(List<?> source, |
singleton
1 | public static <T> Set<T> singleton(T o) |
返回一个不可变的集合只包含指定对象。
一般可以配合removeAll使用,因为removeAll接受的参数是Set
例子
1 | import java.util.*; |
List1 value: [Two, Three, One, Two, Three]
The SingletonList is :[Two, Three, Two, Three]