Java-Collections类的使用

1、Collections类的介绍

java.utilCollections类表示集合工具类,包含一些操作集合的静态方法(工具方法)

2、Collections常用方法的使用

  1、往指定的集合添加多个元素

    addAll(Collection<? super T>c,T ... elements) 往指定的结合添加多个元素

List<Integer> list = new ArrayList<>();
Collections.addAll(list,1,2,3);

  2、打乱集合元素的顺序

    shuffle(List<?> list)

Collections.shuffle(list);

  3、集合的元素排序

    sort(List<T>list) 按照默认的规则排序   

        //默认升序排序  已Integer为例
        Collections.sort(list);
        System.out.println("默认排序后的元素"+list);
        //编写降序排序
        Collections.sort(list, new Comparator<Integer>() {
            public int compare(Integer o1, Integer o2) {
                return o2-o1;
            }
        });
        System.out.println("降序排序后的元素"+list);        

  4、集合元素的查找

    Collections.binarySearch(List<? extends Comparable<? super T>>list,T key)

             注意,查询元素前需要sort 默认排序


    

    

 

posted @ 2022-05-06 15:26  刘靖凯  阅读(328)  评论(0编辑  收藏  举报