【集合】Collections工具类使用技巧盘点总结

来源:互联网 发布:php大牛博客 编辑:程序博客网 时间:2024/06/04 00:48

Collections是专门操作数组的工具类。其常见的方法如下:

提供包括元素的排序、查询、修改等操作,还实现将集合对象设置为不可变类,对集合对象实现同步控制等。

import java.util.*;public class TestCol { /**  * @param args  */ public static void main(String[] args) {  // TODO Auto-generated method stub  ArrayList al = new ArrayList();  al.addAll(a1,"9","3","-3","0","0","5");  al.add(1);  al.add(-2);  al.add(7);  System.out.println(al);  //输出最大、最小值  System.out.println(Collections.max(al));  System.out.println(Collections.min(al));  //替换  Collections.replaceAll(al, 0, 1);  System.out.println(al);  //判断-5在集合中出现的次数  System.out.println(Collections.frequency(al, -5));  //排序  Collections.sort(al);  System.out.println(al);  //二分查找  System.out.println(Collections.binarySearch(al, -5)); }}
以及copy方法:

List<String> list1 = new ArrayList<String>();Collections.addAll(list1, "1", "2", "3", "4");List<String> list2 = new ArrayList<String>();Collections.addAll(list2, "a", "b", "c");Collections.copy(list2, list1);

comparable方法:

List<String> list1 = new ArrayList<String>();Collections.addAll(list1, "5", "3", "2", "4");  Collections.sort(list1);System.out.println(list1);

输出结果:
[2, 3, 4, 5]

shuffle方法:随机打乱集合中元素的位置

同步控制:

public class TestSynchronized { /**  * @param args  */ public static void main(String[] args) {  // TODO Auto-generated method stub  Collection c = Collections.synchronizedCollection(new ArrayList());  List l = Collections.synchronizedList(new ArrayList());  Set s = Collections.synchronizedSet(new HashSet());  Map m = Collections.synchronizedMap(new HashMap()); }}

以上就是在我进行java的第三遍总结的时候查找整理的资料,总结了一下,这个类在操作集合的时候确实很方便。

0 0