Collections 工具类
基本介绍
(1)Collections 中提供了一系列静态方法 对集合元素进行排序,查询和修改等操作
(2)操作对象:集合
常用方法一览表
方法 描述 reverse(List<?> list)反转 List 中元素的顺序。 sort(List<T> list)对 List 中的元素按自然顺序进行排序。 sort(List<T> list, Comparator<? super T> c)使用指定的 Comparator 对 List 进行排序。 shuffle(List<?> list)随机打乱 List 中元素的顺序(即随机排序 ) fill(List<? super T> list, T obj)将 List 中的所有元素设置为指定的值。 swap(List<?> list, int i, int j)交换 List 中指定位置的元素。 max(Collection<? extends T> coll)返回集合中的最大元素。 max(Collection<? extends T> coll, Comparator<? super T> comp)可以传入比较器 指定最大的含义min(Collection<? extends T> coll)返回集合中的最小元素。 min(Collection<? extends T> coll, Comparator<? super T> comp)可以传入比较器 指定最小的含义frequency(Collection<?> c, Object o)返回指定元素在集合中出现的次数。 copy(List<? super T> dest, List<? extends T> src)把源集合src元素复制到目标集合dest中 replaceAll(List<T> list, UnaryOperator<T> operator)用指定的操作替换 List 中的每个元素。
copy()方法的说明
源码
public static < T > void copy ( List < ? super T > dest, List < ? extends T > src) {
int srcSize = src. size ( ) ;
if ( srcSize > dest. size ( ) )
throw new IndexOutOfBoundsException ( "Source does not fit in dest" ) ;
if ( srcSize < COPY_THRESHOLD ||
( src instanceof RandomAccess && dest instanceof RandomAccess ) ) {
for ( int i= 0 ; i< srcSize; i++ )
dest. set ( i, src. get ( i) ) ;
} else {
ListIterator < ? super T > di= dest. listIterator ( ) ;
ListIterator < ? extends T > si= src. listIterator ( ) ;
for ( int i= 0 ; i< srcSize; i++ ) {
di. next ( ) ;
di. set ( si. next ( ) ) ;
}
}
}
首先计算源结合的大小,如果源集合的大小大于了目标集合的大小就会抛出异常 IndexOutOfBoundsException
使用注意点 :复制之前需要对目标集合扩容(赋空字符,大小和源集合大小一致 )
代码示例
public class pra {
public static void main ( String [ ] args) {
ArrayList arrayList = new ArrayList ( ) ;
ArrayList list = new ArrayList ( ) ;
for ( int i = 0 ; i < 10 ; i++ ) {
arrayList. add ( i) ;
}
for ( int i = 0 ; i < 10 ; i++ ) {
list. add ( "" ) ;
}
Collections . copy ( list, arrayList) ;
System . out. println ( "arrayList:" + arrayList) ;
System . out. println ( "list:" + list) ;
}
}
arrayList:[ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ]
list:[ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ]