Collections 类来源于 java.util.Collections,从 java.lang.object继承.

  此类完全由在 collection 上进行操作或返回 collection 的静态方法组成。它包含在 collection 上操作的多态算法,即“包装器”,包装器返回由指定 collection 支持的新 collection,以及少数其他内容。如果为此类的方法所提供的 collection 或类对象为 null,则这些方法都将抛出 NullPointerException

  类  java.util.Collections (不是 Collection 的接口)提供了一些静态方法,这些方法实现了基于容器接口(Set、Link、Map)的一些常用方法

  1. void sort(List<?> list) :对指定列表 List 容器内的进行排序;

  2. void shuffle(List<?> list):对指定列表 List 容器内的对象进行随机排列;

  3. void reverse(List<?> list):对指定列表 List 容器内的对象进行逆序排列;

  4. void fill(List<? > list,  object):用一个特定的对象重写整个list容器;

  5. void copy(List<?> dest,  List<? > src):将所有元素从一个列表复制到另一个列表;

  6. synchronizedCollection(Collection<T> c):返回指定 collection 支持的同步(线程安全的)collection。为了保证按顺序访问,必须通过返回的 collection 完成所有对底层实现 collection 的访问;

  7. synchronizedList(List<T> list):返回指定列表支持的同步(线程安全的)列表;

        List list = Collections.synchronizedList(new ArrayList());
          ...
        synchronized(list) {
            Iterator i = list.iterator(); // Must be in synchronized block
            while (i.hasNext())
                 foo(i.next());
         }

Demo_1:

class Test {
	public static void main(String[] args) {
		LinkedList<String> l1 = new LinkedList<String>();
		for(int i=0;i<=9;i++){
			l1.add("a"+i);
		}
		System.out.println(l1); // 输出: [a0, a1, a2, a3, a4, a5, a6, a7, a8, a9]
		Collections.shuffle(l1); // 随机排列
		System.out.println(l1); // 输出:[a4, a7, a6, a3, a5, a0, a8, a2, a1, a9]
		Collections.reverse(l1); // 逆序排列
		System.out.println(l1); // 输出:[a9, a1, a2, a8, a0, a5, a3, a6, a7, a4]
		Collections.sort(l1); // 排序
		System.out.println(l1); // 输出:[a0, a1, a2, a3, a4, a5, a6, a7, a8, a9]
		System.out.println(Collections.binarySearch(l1, "a4")); // 折半查找输出:4
	}
}

 

posted on 2017-04-26 20:46  牧羊人的世界  阅读(179)  评论(0编辑  收藏  举报