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);
List<String> list1 = new ArrayList<String>(); Collections.addAll(list1, "5", "3", "2", "4"); Collections.sort(list1); System.out.println(list1);
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()); } }