Java集合框架——collections工具类
collections工具类
collections工具类概述
conllections类是操作接口collecton和map的工具类。注意collections并不是collection接口的实现类。
collections常用方法
collections类中提供了一系列静态方法为对集合进行排序、查询和修改等操作,还提供了对集合对象设置不可变、对集合对象实现同步控制等方法。
reverse(List) 反转元素顺序
shuffle(List) 随机排序
sort(List) 自然排序(升序)
sort(List, Comparator) 定制排序
swap(List list,int i,int j)将指定集合List的第i个元素与第j个元素交换
Object max|min(Collection) 获得最大、小值
frequency(Collection,Object) 返回集合中出现元素的次数
copy(list,dist)将dist的值替换到list当中,注意list的长度要大于dist
replaceAll(List list,Object oldVal, Object newVal)用新值替换list对象的旧值
public static void Test01(){
List ar1 = new ArrayList();
ar1.add(123);
ar1.add(349);
ar1.add(890);
ar1.add(768);
System.out.println(ar1);
// reverse(List) 反转元素顺序
Collections.reverse(ar1);
System.out.println(ar1);
//shuffle(List) 随机排序
Collections.shuffle(ar1);
System.out.println(ar1);
//sort(List) 自然排序(升序)
Collections.sort(ar1);
System.out.println(ar1);
//sort(List, Comparator) 定制排序
Collections.swap(ar1,2,3);
System.out.println(ar1);
}
public static void Test02(){
List ar1 = new ArrayList();
ar1.add(123);
ar1.add(349);
ar1.add(890);
ar1.add(768);
System.out.println(ar1);
// Object max|min(Collection)
System.out.println(Collections.max(ar1));
System.out.println(Collections.min(ar1));
// frequency(Collection,Object) 返回集合中出现元素的次数
System.out.println(Collections.frequency(ar1,123));
//copy(list,dist)将dist的值替换到list当中,注意list的长度要大于dist
List ar2=Arrays.asList(new Object[ar1.size()]);
Collections.copy(ar2,ar1);
System.out.println(ar2);
}
Collecyions工具类与多线程
我们知道,在集合中的常用类如ArrayList、HashMap都是线程不安全的。在使用是要格外小心,而在Collections 类中就提供了多种synchronizedXxxx方法。该方法可以将指定集合包装成线程同步同步的集合,从而解决多线程并发访问集合时的线程安全问题。例如:
List list1=Collections.synchronizedList(list);
返回的list1就是线程安全的
作者:二十四桥明月夜436
来源链接:https://blog.csdn.net/qq_61897054/article/details/123454086