一.Collections
Collections类全部是静态函数,主要是用来对Collection中的某个元素进行操作和对Collection进行操作
A.对某个元素进行操作
1. 查询
static <T> int binarySearch(List<? extends Comparotor<? super T>> list, T key);返回key的index,假如不存在返回-1,假如list有多个相同的key,则不能确定返回哪一个的index
下面这个方法类似
binarySearch(List<? extends T> list, T key,Comparator<?
super T> c)
|
|
2.获得某个元素个数
static int frequency(Collection<?> c,Object key)返回c中key的个数
3.替换指定元素
static void replace(List<T> list,T old,T new)将list中所有old替换为new
4.交换两个元素
static void swap(List<?> list, int i ,int j)建好index为i和j的元素
5.获得Collection中最大和最小的元素
static <T extends
Object & Comparable<? super T>> T max(Collection<? extends T> c)
返回c中大元素
以下方法类似
static <T extendsObject &
Comparable<? super T>> T min(Collection<? extends T> c)
static T min(Collection<? extends T> c,
Comparator<?
super T> comp
)
static
T max(Collection<? extends T> c,
Comparator<? super T> comp
)
B.对Collection的操作
1.检查Collection中的类型
static
<E> Collection<E> checkedCollection(Collection<? extends E> c,Class<E> type);返回c中类型符合的元素组成的Collection,剩下还有checkedList(),checkedMap(),checkedSet(),checkedSortedSet(),checkedSortedMap();
2.获得空的Collection
static <T> Iterator<T>
emptyIterator();返回一个空的Iterator,且不可改变
类似方法:emptyEnumeration(),emptyList(),emptySet(),emptyMap(),emptyListIterator();
3.两个Collection的复制
static <T> void copy(List<? super T> dest,List<? extends T> src);将src复制到dest
4.检查两个Collection是否有相同元素
static boolean disjiont(Collection<?> c1,Collection<?> c2);
5.获得在ListB在ListA中index
static int indexOfSubList(List<?> source,List<?> target );
eg: source {1,2,3,4,5},targe{3,4},indexOfSubList(source,targe)返回值就是2
类似方法static int lastIndexOfSubList(List<?> source,List<?> targe);
6.List排序
static <T extends
Comparable<? super T>> void
sort(List<T> list);将list顺序排序
static void reverse(List<?> list);反序
static void shuffle(List<?> list);使用默认的随机规则将list重新随机排序
static void rotate(List<?> list,int distance);将该list前移distance位,
eg: list{1,2,3,4,5,6} rotate(list,3) ,list变为{4,5,6,1,2,3}
7.获得异步Collection
static <T> Collection<T>
synchronizedCollection(Collection<T> c);使用该方法是获得了异步Collection,但是这个异步是部分异步的,根据官方api,使用异步Collection后任然要手动调用synchronized(c){}
查看源代码:
SynchronizedCollection(Collection<E> c) {
if (c==null)
throw new NullPointerException();
this.c = c;
mutex = this;
}
public boolean add(E e) {
synchronized(mutex) {return c.add(e);}
}
public boolean remove(Object o) {
synchronized(mutex) {return c.remove(o);}
}
//没有进行同步操作
public Iterator<E> iterator() {
return c.iterator(); // 由用户自己手动同步
}
所有在进行对该Collection进行处理add和remove以外的原子操作时,任然需要synchronized操作
8.获得不可改变的Collection
Collections.EMPTY_LIST;这是一个不可改变的空的list
类似有Collections.EMPTY_MAP,Collections.EMPTY_SET,emptyEnumration(),emptyList()等
static <T> Set<T>
Singleton(T o)返回一个有一个o元素的不可变的set
static <T> Collection<T>
unmodifiableCollection(Collection<?
extends T> c)
返回包含c中所有元素的不可变的Collection