Collections工具类使用例子

package day1105Collections;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

public class TestCollections {
    public static void main(String[] args) {
        Listlist=new ArrayList();
        /**
         * 添加
         */
        Collections.addAll(list, "3","12","14","16","3","18","2","1","9","37","47","14","21","10","8","2","1");
        System.out.println(list);
        Collections.shuffle(list);
        System.out.println(list);
        Collections.swap(list, 3, 4);
        System.out.println(list);
        Collections.sort(list);
        System.out.println(list);
        
        /**
         * 排序
         * sort()方法可以使用一个比较器对象来对数据进行比较
         * new 是新建匿名类实例,该匿名类继承Comparator接口
         * Collections.sort(list,比较器对象)
         * 要实现compare()方法
         */
        Collections.sort(list,new Comparator() {

            /**
             * compare(o1,o2)
             * o1和o2比大小
             * o1大返回正数
             * o1小返回负数
             * 相同返回0
             * 
             * 
             * o1 -2100000000
             * o2 1000000000
             * o1-o2溢出
             */
            @Override
            public int compare(String o1, String o2) {
                //字符串转成int
                int a=Integer.parseInt(o1);
                int b=Integer.parseInt(o2);
                if(ab)
                {
                    return 1;
                }else
                {
                    return 0;
                }
            }
        });
        System.out.println(list);
        for (String s : list) {
            System.out.print(s+" ");
        }
        System.out.println();
        for (Iterator iterator = list.iterator(); iterator.hasNext();) {
            String s = iterator.next();
            System.out.print(s+" ");
            
        }
        System.out.println();
        System.out.println(Collections.binarySearch(list, "2",new Comparator() {

            public int compare(String o1, String o2) {
                //字符串转成int
                int a=Integer.parseInt(o1);
                int b=Integer.parseInt(o2);
                if(ab)
                {
                    return 1;
                }else
                {
                    return 0;
                }
            }
            
        }));
    }
}

运行结果

[18, 10, 21, 37, 14, 12, 1, 47, 3, 2, 2, 9, 14, 3, 1, 16, 8]
[18, 10, 21, 14, 37, 12, 1, 47, 3, 2, 2, 9, 14, 3, 1, 16, 8]
[1, 1, 10, 12, 14, 14, 16, 18, 2, 2, 21, 3, 3, 37, 47, 8, 9]
[1, 1, 2, 2, 3, 3, 8, 9, 10, 12, 14, 14, 16, 18, 21, 37, 47]
1 1 2 2 3 3 8 9 10 12 14 14 16 18 21 37 47 
1 1 2 2 3 3 8 9 10 12 14 14 16 18 21 37 47 
3

你可能感兴趣的:(Collections工具类使用例子)