Java Collections集合的工具类使用方法

import java.util.*;
public class test1 {
    public static void main(String[] args){
        // Collections集合的工具类使用方法
        /*
            1.Collections.addAll(list,l1,l2,l3...) 可变参数添加对象
            2.Collections.shuffle(list) 打乱集合中的元素顺序
            3.Collection.sort(list, new Comparator(){@Override }) 为集合中的自定义数据类型指定顺序排序
            4.(返回int型的index) Collections.binarySearch(list, 要查找的元素)二分查找 首先数据得有升序的规律时使用
            5.Collections.copy(newlist, list) 拷贝集合 新的集合长度不能小于源集合
            6.Collections.fill(list,要填充的元素) 为集合填充指定的元素
            7.Collections.swap(list ,index1,index2); 交换集合中指定的元素
         */


        // 1.Collections.addAll(list,l1,l2,l3...)
        // 创建集合对象
        List stu = new ArrayList<>();
        student s1 = new student("1",1);
        student s2 = new student("2",2);
        student s3 = new student("3",3);
        student s4 = new student("4",4);
        // 可变参数添加对象
        Collections.addAll(stu,s1,s2,s3,s4);
        System.out.println(stu);
        // 2.打乱集合中的元素顺序
        Collections.shuffle(stu);
        System.out.println(stu);
        // 3.Collection.sort(list, new Comparator(){@Override }) 为集合中的自定义数据类型指定顺序排序
        Collections.sort(stu, new Comparator() {
            @Override
            public int compare(student o1, student o2) {
                return o1.getAge()-o2.getAge();
            }
        });
        System.out.println(stu);
        // 4.Collections.binarySearch(list, 要查找的元素)二分查找(首先数据得有升序的规律时使用)
        List intArr = new ArrayList<>();
        Collections.addAll(intArr,1,2,3);
        int r= Collections.binarySearch(intArr,2);
        System.out.println(r);//1
        // 5.Collections.copy(newlist, list) 拷贝集合
        // 初始化了一个固定长度的数组对象
        List intArr2 = Arrays.asList(new Integer[intArr.size()]);
        System.out.println(intArr2.size());//3
        Collections.copy(intArr2,intArr);
        System.out.println(intArr2);// [1, 2, 3]
        // 6.Collections.fill(list,要填充的元素) 为集合填充指定的元素 (全部填充)
        Collections.fill(intArr,4);
        System.out.println(intArr);// [4, 4, 4]
        // 7.Collections.swap(list ,index1,index2); 交换集合中指定的元素
        List li = new ArrayList<>();
        Collections.addAll(li,1,3,5,2,5);
        Collections.swap(li,0,1);
        System.out.println(li);// [3, 1, 5, 2, 5]

    }
}

你可能感兴趣的:(java,windows,python)