shaoshuai888

Collections集合工具类

一.Collection与Collections

  Collection 是所有单列集合的根接口

  Collection 是操作集合的工具类

 

二.Collections中常见的方法:(大都是static方法,通过类名直接调用)

  static boolean addALL(Collction c, T... elements):  向集合中批量添加元素,参数c表示集合,参数elements表示要向此集合中添加哪些元素

  static void shuffle(List list):  对集合中的内容打乱顺序

    

        ArrayList<String> list = new ArrayList<>();
        //Collections工具类中的addAll可以直接批量添加
        Collections.addAll(list, "aa", "bb", "cc", "dd");
        System.out.println(list);

        //static void shuffle​(List list): 对集合中的内容打乱顺序。
        Collections.shuffle(list);
        System.out.println(list);    

 

  static void sort(List list):  对集合中的内容排序

  自然排序:  使用泛型类型必须要实现Comparable接口,实现这个接口才表示这个类的对象具备了排序的功能

  static void sort(List list,Comparator c):  对集合中的内容排序

  比较器排序:  事物本身不会排序,需要借助比较器对象进行排序

  比较器排序需要创建一个Rule类或者匿名内部类,我们用Rule类和Test类中代码做演示:

  

    public class Rule implements Comparator<Student>{//比较器类必须实现Comparator
    /*
        这个方法用来比较o1和o2这两个参数对象谁大谁小。
        如果返回值是负数,那么表示o1小于02
        如果返回值是0表示这两个对象相等。
        如果返回值是正数,表示o1大于o2

        公式: 升序就是1减2
     */
    @Override
    public int compare(Student o1, Student o2) {
        return o1.getAge() - o2.getAge();
        }
    }

    
    //Test类中代码如下:
   //使用比较器排序对集合中的内容进行排序
        Collections.sort(list, new Rule());

 

  

posted on 2018-08-30 17:57  shaoshuai888  阅读(130)  评论(0编辑  收藏  举报

导航