Collections总结

Collections(理解)   

    (1)是针对集合进行操作的工具类

    (2)面试题:Collection和Collections的区别

        A:Collection 是单列集合的顶层接口,有两个子接口List和Set

        B:Collections 是针对集合进行操作的工具类,可以对集合进行排序和查找等

    (3)常见的几个小方法:

        A:public static <T> void sort(List<T> list):排序 默认情况下是自然顺序。

        B:public static <T> int binarySearch(List<?> list,T key):二分查找

        C:public static <T> T max(Collection<?> coll):最大值

        D:public static void reverse(List<?> list):反转

        E:public static void shuffle(List<?> list):随机置换

    (4)案例

        A:ArrayList集合存储自定义对象的排序      


public class Student implements Comparable<Student> {

    private String name;

    private int age;



   //构造器,getXXX+setXXx....

    @Override

    public int compareTo(Student s) {

        int num = this.age - s.age;

        int num2 = num == 0 ? this.name.compareTo(s.name) : num;

        return num2;

    }

}
/*

 * Collections可以针对ArrayList存储基本包装类的元素排序,存储自定义对象排序需要比较器。

 */

public class CollectionsDemo {

    public static void main(String[] args) {

        // 创建集合对象

        List<Student> list = new ArrayList<Student>();



        // 创建学生对象

        Student s1 = new Student("林青霞", 27);

        Student s2 = new Student("风清扬", 30);

        Student s3 = new Student("刘晓曲", 28);

        Student s4 = new Student("武鑫", 29);

        Student s5 = new Student("林青霞", 27);



        // 添加元素对象

        list.add(s1);

        list.add(s2);

        list.add(s3);

        list.add(s4);

        list.add(s5);



        // 排序

        // 自然排序

        // Collections.sort(list);

        // 比较器排序

        // 如果同时有自然排序和比较器排序,以比较器排序为主

        Collections.sort(list, new Comparator<Student>() {

            @Override

            public int compare(Student s1, Student s2) {

                int num = s2.getAge() - s1.getAge();

                int num2 = num == 0 ? s1.getName().compareTo(s2.getName())

                        : num;

                return num2;

            }

        });



        // 遍历集合

        for (Student s : list) {

            System.out.println(s.getName() + "---" + s.getAge());

        }

    }

}
发布了114 篇原创文章 · 获赞 52 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Smile_Sunny521/article/details/89703503