Collections
1.概述
Collections是一个针对集合进行操作的工具类,它里面的方法都是静态方法,所以可以直接通过类名.方法名
调用方法。
Collection和Collections的区别:
- Collection是集合的顶层接口
- Collections是操作集合的工具类
2.常用方法
演示所用集合:
List<Integer> l=new ArrayList<>();
l.add(15);
l.add(6);
l.add(43);
l.add(24);
l.add(56);
l.add(9);
System.out.println(l); //[15, 6, 43, 24, 56, 9]
public static <T extends Comparable<? super T>> void sort(List< T> list)
传入一个集合,对集合中的元素进行排序,此时元素要实现Comparable接口,排序为自然排序。例,
Collections.sort(l);
System.out.println(l); //[6, 9, 15, 24, 43, 56]
public static < T> int binarySearch(List<? extends Comparable<? super T>> list, T key)
二分查找方法,使用前必须先进行排序否则无法得到正确结果。例,
System.out.println(Collections.binarySearch(l, 24)); //3
System.out.println(Collections.binarySearch(l, 50)); //-6
有关在集合中找不到的元素的返回值计算请看源码!
public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll)
public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll)
返回集合中的最大值和最小值。
public static void reverse(List<?> list)
将集合中的元素反转。例,
System.out.println(l); //[15, 6, 43, 24, 56, 9]
Collections.reverse(l);
System.out.println(l); //[9, 56, 24, 43, 6, 15]
public static void shuffle(List<?> list)
将集合中的元素随机换位置。例,
System.out.println(l); //[15, 6, 43, 24, 56, 9]
Collections.shuffle(l);
System.out.println(l); //[24, 6, 9, 56, 15, 43]
3.线程安全
虽然Collection和Map下有一些线程安全的类,例如Vector和Hashtable。但是通常不会使用它们,而是使用Collections中的一些方法将集合变成线程安全的:
public static < T > Collection< T > synchronizedCollection(Collection< T > c)
public static < T > List< T > synchronizedList(List< T > list)
public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m)
public static < T > Set< T > synchronizedSet(Set< T > s)