Collections 操作集合的工具类

来源:互联网 发布:聚划算抢购软件神器 编辑:程序博客网 时间:2024/05/12 12:11

import java.awt.*;
import java.util.*;
import java.util.List;

/**
 * 操作集合的工具类
 * Java提供了一个操作Set,List和Map 等集合的工具类:Collections。该工具类里提供了大量方法对集合元素进行排序、
 * 查询和修改操作,还提供里对集合对象设置为不可变,对集合对象实现同步控制等方法
 * @author liyongyong
 *
 */


public class TestCollections {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ArrayList list = new ArrayList();
       
        list.add(2);
        list.add(8);
        list.add(1);
        list.add(4);
        Integer intValue = new Integer(5);
       
        /*****************************排序操作*******************************/
        System.out.println(list);        //顺序输出元素
        Collections.reverse(list);        //将list集合元素反转
        System.out.println(list);
        Collections.shuffle(list);        //对list集合元素进行随机排序
        System.out.println(list);
        Collections.swap(list, 1, 3);    //将下标为1,3交换
        System.out.println(list);
        Collections.rotate(list, 2);    //当参数为正数时,将list集合的后n个元素移到前面;否则,把前n个移到后面
        System.out.println(list);
        Collections.sort(list);            //将list集合排序
        System.out.println(list);
       
        /*****************************查找、替换操作*******************************/
        System.out.println(Collections.max(list));    //输出最大元素
        System.out.println(Collections.min(list));    //输出最小元素
//        Collections.fill(list, intValue);            //把集合list全部复制为intValue
//        System.out.println(list);
        Collections.replaceAll(list, 8, 11);        //使用一个11(新值)替换为List对象所有的8(旧值)
        System.out.println(list);
       
        ArrayList list2 = new ArrayList();
        list2.add(2);
        list2.add(4);
        System.out.println(Collections.indexOfSubList(list, list2));    //返回子list2在母list对象中第一次出现的位置索引   
        System.out.println(Collections.frequency(list, intValue));        //返回集合中等于指定对象(intValue)的元素数量       
       
       
        /*****************************同步控制*******************************/
        Collection c = Collections.synchronizedCollection(new ArrayList());
        List list3 = Collections.synchronizedList(new ArrayList());
        Set set = Collections.synchronizedSet(new HashSet());
        Map map = Collections.synchronizedMap(new HashMap());
           
    }
}