Java基础三十四(集合)

一、集合框架的概述

  • 1.集合、数组都是对多个数据进行存储操作的结构,简称Java容器
      说明:此时的存储,主要指的是内存层面的存储,不涉及到持久化存储(.txt,.jpg,.avi,数据库)

  • 2.数组在存储多个数据方面的特点:
      >一旦初始化以后,其长度就确定了。
      >数组一旦定义好,其元素的类型就确定了。只能操作指定类型的数据。
      比如: String arr[];int[] arr1;Object[] arr2;
      存在缺点:
        长度不能修改
        数组中提供的方法非常有限,对于添加、删除、插入数据等操作,非常不便,同事效率不高
        获取数组中实际元素的个数需求,数组中没有现成的属性或方法可用
        数据存储数据的特点:有序、可重复。对于无须、不可重复的需求,不能满足

二、集合框架

  |—Collection接口:单列集合,用来存储一个一个的对象
    |—List接口:存储有序的、可重复的数据。–>“动态数组”
      |—ArraysList、LinkedList、Vector
    |—Set接口:存储无序的、不可重复的数据。–>高中“集合”
      |—HashSet、LinkedHashSet、TreeSet
   |—Map接口:双列集合,用来存储一对(key-value)一对的数据 -->高中函数 y = f(x)
    |—HashMap、LinkHashMap、TreeMap、Hashtable、Properties

三、Collection接口中的方法的使用

  向Collection接口的实现类的对象中添加数据obj时,要求obj所在类重写equals()

public class CollectionTest {

    @Test
    public void test1(){
        Collection coll = new ArrayList();

        //add(Object e):将元素e添加到集合coll中
        coll.add("AA");
        coll.add("BB");
        coll.add("123");//自动装箱
        coll.add(new Date());

        //size():获取添加元素的个数
        System.out.println(coll.size());//4

        //addAll(Collection coll1):将coll1集合中的元素添加到当前的集合中
        Collection coll1 = new ArrayList();
        coll1.add(456);
        coll1.add("cc");
        coll.addAll(coll1);

        System.out.println(coll.size());//6
        System.out.println(coll.toString());//[AA, BB, 123, Mon Nov 23 09:48:46 CST 2020, 456, cc]

        //clear:清空集合元素
        coll.clear();

        //isEmpty():判断当前集合是否为空
        System.out.println(coll.isEmpty());//false //clear后为true
    }

    @Test
    public void test2(){

        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new String("Tom"));
        coll.add(false);
//        Person p1 = new Person("Jerry", 20);
//        coll.add(p1);
        coll.add(new Person("Jerry", 20));

        //contains(Object obj):判断当前集合中是够包含obj
        //在判断时会调用obj对象所在类的equals()
        boolean contains = coll.contains(123);
        System.out.println(contains);//true

        System.out.println(coll.contains(new String("Tom")));//true
//        System.out.println(coll.contains(p1);//true
        System.out.println(coll.contains(new Person("Jerry", 20)));//对象所在类的equals方法进行比较false
        //重写equals方法后,变为true

        //containsAll(Collection coll1):判断形参coll1中的所有元素是否都存在当前集合中
        Collection coll1 = Arrays.asList(123, 456);
        Collection coll2 = new ArrayList();
        coll2.add(123);
        coll2.add(456);
        System.out.println(coll.containsAll(coll1));//true
        System.out.println(coll.containsAll(coll2));//true
    }

    @Test
    public void test3(){
        //remove(Object obj):从当前集合中移除obj元素,调用equals进行匹配
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new Person("Jerry", 20));
        coll.add(new String("Tom"));
        coll.add(false);

        coll.remove(123);
        System.out.println(coll);//[456, Person{name='Jerry', age=20}, Tom, false]

        coll.remove(new Person("Jerry", 20));
        System.out.println(coll);//[456, Tom, false]

        //removeAll(Collection coll1):从当前集合中移除coll1中所有的元素
        Collection coll1 = Arrays.asList(456, 789);
        coll.removeAll(coll1);
        System.out.println(coll);//[Tom, false]
    }

    @Test
    public void test4(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new Person("Jerry", 20));
        coll.add(new String("Tom"));
        coll.add(false);

        //retainAll(Collection coll1):交集:获取当前集合和coll1集合的交集,并返回给当前集合
//        Collection coll1 = Arrays.asList(123, 456, 789);
//        coll.retainAll(coll1);
//        System.out.println(coll);//[123, 456]

        //equals(Object obj):要想返回true,需要当前集合和形参集合的元素都相同
        Collection coll3 = new ArrayList();//ArrayList有序
        coll3.add(123);
        coll3.add(456);
        coll3.add(new Person("Jerry", 20));
        coll3.add(new String("Tom"));
        coll3.add(false);

        System.out.println(coll.equals(coll3));//true
        //123/456交换顺序后,false
    }

    @Test
    public void test5(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new Person("Jerry", 20));
        coll.add(new String("Tom"));
        coll.add(false);

        //hashCode():返回当前对象的哈希值
        System.out.println(coll.hashCode());//701070075

        //集合 --> 数组:toArray()
        Object[] arr = coll.toArray();
        for (int i = 0; i < arr.length; i++){
            System.out.println(arr[i]);
        }
        //123
        //456
        //Person{name='Jerry', age=20}
        //Tom
        //false

        //拓展:数组 --> 集合:调用Arrays类的静态方法asList()
        List<String> list = Arrays.asList(new String[]{"AA", "BB", "CC"});
        System.out.println(list);//[AA, BB, CC]

        List arr1 = Arrays.asList(new int[]{123, 456});
        System.out.println(arr1);//[[I@621be5d1]
        System.out.println(arr1.size());//1认为数组只有一个元素

        List arr2 = Arrays.asList(123,456);
        System.out.println(arr2);//[123, 456]

        List arr3 = Arrays.asList(new Integer[]{123,456});
        System.out.println(arr3);//[123, 456]

        //iterator():返回Iterator接口的实例,用于遍历集合元素。放在IteratorTest.java中测试
    }
}
public class Person {
    private String name;
    private int age;

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        System.out.println("person equals");
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return age == person.age &&
                Objects.equals(name, person.name);
    }

//    @Override
//    public int hashCode() {
//        return Objects.hash(name, age);
//    }
}

集合元素的遍历操作,使用迭代器Iterator接口

  • 1.内部的方法:hasNext()、next()
  • 2.集合对象每次调用iterator()方法都得到一个全新的迭代及对象,默认游标都在集合的第一个元素之前
  • 3.内部定义了remove(),可以在遍历的时候删除集合中的元素。此方法不同于集合直接调用remove()
public class IteratorTest {

    @Test
    public void test1(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new Person("Jerry", 20));
        coll.add(new String("Tom"));
        coll.add(false);

        Iterator iterator = coll.iterator();

        //方式一:
//        System.out.println(iterator.next());//123
//        System.out.println(iterator.next());//456
//        System.out.println(iterator.next());//Person{name='Jerry', age=20}
//        System.out.println(iterator.next());//Tom
//        System.out.println(iterator.next());//false
//        System.out.println(iterator.next());//java.util.NoSuchElementException

        //方式二:
//        for (int i = 0; i < coll.size(); i++){
//            System.out.println(iterator.next());
//        }

        //方式三:推荐使用
        //hasNext()判断是否还有下一个元素
        while(iterator.hasNext()){
            //next():①指针下移②将下移以后集合位置上的元素返回
            System.out.println(iterator.next());
        }

    }

    @Test
    public void test2(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new Person("Jerry", 20));
        coll.add(new String("Tom"));
        coll.add(false);

        //错误方式一:
//        Iterator iterator = coll.iterator();
//        while((iterator.next()) != null){
//            //next():①指针下移②将下移以后集合位置上的元素返回
//            System.out.println(iterator.next());
//        }
        //456
        //Tom
        //java.util.NoSuchElementException

        //错误方式二:
        //集合对象每次调用iterator()方法都得到一个全新的迭代及对象,默认游标都在集合的第一个元素之前
        while(coll.iterator().hasNext()){
            System.out.println(coll.iterator().next());
        }
        //123
        //123
        //123
        //...

    }

    //测试Iterator中的remove()
    @Test
    public void test3(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new Person("Jerry", 20));
        coll.add(new String("Tom"));
        coll.add(false);

        //测试Iterator中的remove()
        //如果还未调用next()或在上一次调用next方法之后已经调用了remove方法,
        //再调用remove会报java.lang.IllegalStateException
        Iterator iterator = coll.iterator();
        while (iterator.hasNext()){
            Object obj = iterator.next();
            if ("Tom".equals(obj)){
                iterator.remove();
//                iterator.remove();//java.lang.IllegalStateException
            }
        }
        //遍历集合
        Iterator iterator1 = coll.iterator();
        while (iterator1.hasNext()){
            System.out.println(iterator1.next());
        }
    }
}

jdk 5.0 新增foreach循环,用于遍历集合、数组

public class ForTest {
    @Test
    public void test1(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new Person("Jerry", 20));
        coll.add(new String("Tom"));
        coll.add(false);

        //for(集合中元素的类型 局部变量 : 集合对象)
        //内部仍然调用了迭代器
        for (Object obj : coll){
            System.out.println(obj);
        }
    }

    @Test
    public void test2(){
        int arr[] = new int[]{1, 2, 3, 4, 5, 6};

        //for(数组中元素的类型 局部变量 : 数组对象)
        for (int i : arr){
            System.out.println(i);
        }
    }

    //练习题
    @Test
    public void test3(){
        String[] arr = new String[]{"MM", "MM", "MM"};
        //方式一:普通for赋值
//        for (int i = 0;i < arr.length; i++){
//            arr[i] = "GG";
//        }
        //GG
        //GG
        //GG

        //方式二:增强for循环
        //重新赋了一个s的值,修改s不改变原有数组中的元素
        for (String s : arr){
            s = "GG";
        }
        //MM
        //MM
        //MM

        for (int i = 0; i < arr.length; i++){
            System.out.println(arr[i]);
        }
    }
}
  • 1.|—Collection接口:单列集合,用来存储一个一个的对象
      |—List接口:存储有序的、可重复的数据。–>“动态数组”
        |—ArraysList:作为List接口的主要实现类,线程不安全的,效率高;底层使用Object[] elementData存储
        |—LinkedList:对于频繁的插入、删除操作,使用此类效率比ArrayList高;底层使用双向链表存储
        |—Vector:作为List接口的古老实现类,线程安全,效率低;底层使用Object[] elementData存储
  • 2.ArrayList的源码分析:
      2.1jdk7
        ArrayList list = new ArrayList();//底层创建了长度为10的Object[]数组elementData
        list.add(123);//elementData[0] = new Integer(123);
        …
        list.add(11);//如果此次的添加导致底层elementData数组容量不够,则扩容。
        默认情况下,扩容为原来的容量的1.5倍,同时需要将原有数组中的数组复制到新的数组中

  结论:建议开发中使用带参的构造器:ArrayList list = new ArrayList(int capacity);

  2.2jdk 8中ArrayList的变化:
    ArrayList list = new ArrayList();//底层Object[]数组elementData初始化为{},并没有长度为10的数组
    list.add(123);//第一次调用add时,底层才创建了长度为10的数组,并将数据123天假到elementData[0]
     。。。
    后续添加和扩容操作与jdk 7一致
  2.3小结:jkd 7 --> 饿汉式
      jdk 8 --> 懒汉式(延迟数组创建,节省内存)

  • 3.LinkList的源码分析:
      LinkList list = new LinkList();内部声明了Node类型的first和last属性,默认值为null
      list.add(123);//将123封装到Node中,创建了Node对象。

  • 4.Vector的源码分析:jdk 7和jdk 8中通过Vector()构造器创建对象时,底层都创建了长度为10的数组,
      在扩容方面,默认扩容为原来数组长度的2倍。

  • 5.List接口中的常用方法
      面试题:ArraysList、LinkedList、Vector三者的异同?
      同:三个类都实现了List接口,储存数据的特点相同:存储有序的、可重复的数据

public class ListTest {

    @Test
    public void test1(){
        ArrayList list = new ArrayList();
        list.add(123);
        list.add(456);
        list.add("AA");
        list.add(new Person("Tom", 20));
        list.add(456);

        System.out.println(list);//[123, 456, AA, Person{name='Tom', age=20}, 456]

        //void add(int index, Object ele):在index位置插入ele元素
        list.add(1, "bb");
        System.out.println(list);//底层一个个后移//123, bb, 456, AA, Person{name='Tom', age=20}, 456]

        //boolean addAll(int index, Collection eles):从index位置开始将eles中的所有元素添加进来
        List list1 = Arrays.asList(1, 2, 3);

//        list.add(list1);
//        System.out.println(list.size());//7
//        System.out.println(list);//[123, bb, 456, AA, Person{name='Tom', age=20}, 456, [1, 2, 3]]

        list.addAll(list1);
        System.out.println(list.size());//9
        System.out.println(list);//[123, bb, 456, AA, Person{name='Tom', age=20}, 456, 1, 2, 3]

        //Object get(int index):获取指定index位置的元素
        System.out.println(list.get(0));//123

    }

    @Test
    public void test2(){
        ArrayList list = new ArrayList();
        list.add(123);
        list.add(456);
        list.add("AA");
        list.add(new Person("Tom", 20));
        list.add(456);

        //int indexOf(Object obj):返回obj在集合中首次出现的位置。如果不存在,返回-1
        int index = list.indexOf(456);
        System.out.println(index);//1(索引值)

        //int lastIndexOf(Object obj):返回obj在集合中末次出现的位置。如果不存在,返回-1
        System.out.println(list.lastIndexOf(456));//4

        //Object remove(int index):移除指定index位置的元素,并返回此元素
        Object obj = list.remove(0);
        System.out.println(obj);//123
        System.out.println(list);//[456, AA, Person{name='Tom', age=20}, 456]

        //Object set(int index, Object ele):设置指定index位置的元素为ele
        list.set(1, "cc");
        System.out.println(list);//[456, cc, Person{name='Tom', age=20}, 456]

        //List subList(int fromIndex, int toIndex):返回从fromIndex到toIndex位置的左闭又开的子集合
        List subList = list.subList(1, 3);
        System.out.println(list);//[456, cc, Person{name='Tom', age=20}, 456]
        System.out.println(subList);//[cc, Person{name='Tom', age=20}]
    }
}

|—Collection接口:单列集合,用来存储一个一个的对象
  |—Set接口:存储无序的、不可重复的数据。–>高中“集合”
    |—HashSet:作为Set接口的主要实现类 --> 线程不安全的;可以存储null值
      |—LinkedHashSet:作为HashSet子类,遍历其内部数据时,可以按照添加的顺序遍历
            对于频繁的遍历操作,LinkedHashSet效率高于HashSet
    |—TreeSet:可以按照添加对象指定属性进行排序

  • 1.Set接口中没有额外定义新的方法,使用的都是Collection中声明过的方法

  • 2.要求:向Set添加的数据,其所在的类一定要重写hashCode()和equals()
        重写的hashCode()和equals()尽可能保持一致性:相等的对象必须具有相等的散列码

一、Set:存储无序的、不可重复的数据
  以HashSet为例说明:
  1.无序性:不等于随机性。存储的数据在底层数组中并非按照数组索引的顺序添加,而是根据数据的哈希值决定的。

  2.不可重复性:保证添加的元素按照equals()判断时,不能返回true。即相同的元素只能添加一个。

二、添加元素的过程:以HashSet为例

  向HashSet中添加元素a,首先调用元素a所在类的hashCode()方法,计算a的哈希值,
  此哈希值接着通过某种算法计算出在HashSet底层数组中的存放位置(即为:索引位置),
  判断数组此位置上是否已经有元素:
    如果此位置上没有其他元素,则元素a添加成功。 --> 情况1
    如果此位置上有其他元素b(或以链表形式存在多个元素),则比较a与元素b的hash值:
      如果hash值不相同,则元素a添加成功。 --> 情况2
      如果hash值相同,进而需要调用元素a所在类的equals()方法:
        equals()返回true,元素a添加失败
        equals()返回false,则元素a添加成功。 --> 情况3

    对于添加成功的情况2和情况3而言:元素a 与已经存在指定索引位置上数据以链表的方式存储。
    jdk 7:元素a放到数组中,指向原来的元素
    jdk 8:原来的元素在数组中,指向元素a
    总结:七上八下

    HashSet底层:数组+链表的结构

@Test
    public void test1(){
        Set set = new HashSet();
        set.add(456);
        set.add(123);
        set.add(123);
        set.add("AA");
        set.add("CC");
        set.add(new User("Tom", 20));
        set.add(new User("Tom", 20));
        set.add(129);

        Iterator iterator = set.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
        //AA
        //CC
        //129
        //User{name='Tom', age=20}
        //456
        //User{name='Tom', age=20}
        //123
    }

    //LinkedHashSet的使用
    //LinkedHashSet作为HashSet的子类,在添加数据的同时,每个数据还维护了两个引用,记录次数据前一个数据和后一个数据
    //优点:对于频繁的遍历操作,LinkedHashSet效率高于HashSet
    @Test
    public void test2(){
        Set set = new LinkedHashSet();
        set.add(456);
        set.add(123);
        set.add(123);
        set.add("AA");
        set.add("CC");
        set.add(new User("Tom", 20));
        set.add(new User("Tom", 20));
        set.add(129);

        Iterator iterator = set.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
        //456
        //123
        //AA
        //CC
        //User{name='Tom', age=20}
        //129
        //
        //Process finished with exit code 0
    }


}
public class User implements Comparable{

    private String name;
    private int age;

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public User() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        System.out.println("User equals");
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        User user = (User) o;
        return age == user.age &&
                Objects.equals(name, user.name);
    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + age;
        return result;
    }

    //按照姓名从小到大排序,年龄从小到大排序
    @Override
    public int compareTo(Object o) {
        if (o instanceof User){
            User user = (User)o;
//            return this.name.compareTo(user.name);
            int compare = this.name.compareTo(user.name);
            if (compare != 0){
                return compare;
            }else {
                return Integer.compare(this.age, user.age);
            }
        }else{
            throw new RuntimeException("输入类型不匹配");
        }
    }
}
  • 1.向TreeSet中添加的数据,要求是相同类的对象。

  • 2.两种排序方式 自然排序(实现Comparable接口) 和 定制排序(Comparator)

  • 3.自然排序中,比较两个对象是否相同的标准为:compareTo()返回0。不再是equals()

  • 4.定制排序中,比较两个对象是否相同的标准为:compare()返回0。不再是equals()

public class TreeSetTest {

    @Test
    public void test1(){
        TreeSet set = new TreeSet();

        //不能添加不同类的对象
//        set.add(123);
//        set.add(456);
//        set.add("AA");
//        set.add(new User("Tom", 22));

        //举例一:
//        set.add(34);
//        set.add(-34);
//        set.add(24);
//        set.add(11);
//        set.add(8);
        //-34
        //8
        //11
        //24
        //34

        //举例二:
//        set.add("cc");
//        set.add("aa");
//        set.add("bb");
//        set.add("ff");

        //aa
        //bb
        //cc
        //ff

        //举例三
        set.add(new User("Tom", 22));
        set.add(new User("Jerry", 12));
        set.add(new User("Jack", 24));
        set.add(new User("Jack", 56));
        set.add(new User("Mike", 18));



        Iterator iterator = set.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
        //在User中重写Comparable方法后,不重写,报错
        //User{name='Jack', age=24}
        //User{name='Jack', age=56}
        //User{name='Jerry', age=12}
        //User{name='Mike', age=18}
        //User{name='Tom', age=22}

    }

    @Test
    public void test2(){
        Comparator com = new Comparator() {
            //按照年龄从小到大排序
            @Override
            public int compare(Object o1, Object o2) {
                if (o1 instanceof User && o2 instanceof User){
                    User u1 = (User)o1;
                    User u2 = (User)o2;
                    return Integer.compare(u1.getAge(), u2.getAge());
                }else {
                    throw new RuntimeException("输入的数据类型不匹配");
                }
            }
        };

        TreeSet set = new TreeSet(com);

        set.add(new User("Tom", 22));
        set.add(new User("Jerry", 12));
        set.add(new User("Jack", 24));
        set.add(new User("Jack", 56));
        set.add(new User("Mike", 18));
        set.add(new User("Marry", 18));

        //User{name='Jerry', age=12}
        //User{name='Mike', age=18}
        //User{name='Tom', age=22}
        //User{name='Jack', age=24}
        //User{name='Jack', age=56}

        Iterator iterator = set.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }

    }
}

练习
定义一个Employee类
该类包括:private成员变量name、age、birthday,其中birthday为MyDate类的对象;
并为每一个属性定义getter、setter方法
并重写toString方法输出name、age、birthday

public class Employee  implements Comparable{
    private String name;
    private int age;
    private MyDate birthday;

    public Employee() {
    }

    public Employee(String name, int age, MyDate birthday) {
        this.name = name;
        this.age = age;
        this.birthday = birthday;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public MyDate getBirthday() {
        return birthday;
    }

    public void setBirthday(MyDate birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", birthday=" + birthday +
                '}';
    }

    //按照姓名的顺序排
    @Override
    public int compareTo(Object o) {
        if (o instanceof Employee){
            Employee e = (Employee)o;
            return this.name.compareTo(e.name);
        }
//        return 0;
        throw new RuntimeException("传入的数据类型不一致");
    }
}

MyDate类包含:
private成员变量year、month、day:并为每一个属性定义getter、setter方法:

public class MyDate {
    private int year;
    private int month;
    private int day;

    public MyDate() {
    }

    public MyDate(int year, int month, int day) {
        this.year = year;
        this.month = month;
        this.day = day;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public int getMonth() {
        return month;
    }

    public void setMonth(int month) {
        this.month = month;
    }

    public int getDay() {
        return day;
    }

    public void setDay(int day) {
        this.day = day;
    }

    @Override
    public String toString() {
        return "MyDate{" +
                "year=" + year +
                ", month=" + month +
                ", day=" + day +
                '}';
    }
}

创建该类的5个对象,并把这些对象放入TreeSet集合中
分别按一下两种方式对集合中的元素进行排序,并遍历输出:

1.使用Employee实现Comparable接口,并按name排序
2.创建TreeSet时传入Comparable对象,按生日日期的先后顺序进行排序

public class EmployeeTest{

    //问题一:使用自然排序
    @Test
    public void test1(){
        TreeSet set = new TreeSet();

        Employee e1 = new Employee("liudehua", 55,new MyDate(1965, 5, 4));
        Employee e2 = new Employee("zhangxueyou", 43,new MyDate(1988, 5, 4));
        Employee e3 = new Employee("guofucheng", 44,new MyDate(1987, 5, 9));
        Employee e4 = new Employee("liming", 51,new MyDate(1954, 8, 12));
        Employee e5 = new Employee("liangchaowei", 21,new MyDate(1978, 12, 4));

        set.add(e1);
        set.add(e2);
        set.add(e3);
        set.add(e4);
        set.add(e5);

        Iterator iterator = set.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }

    }

    //问题二:按照生日日期的先后顺序
    @Test
    public void test2() {

        TreeSet set = new TreeSet(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if (o1 instanceof Employee && o2 instanceof Employee){
                    Employee e1 = (Employee)o1;
                    Employee e2 = (Employee)o2;

                    MyDate b1 = e1.getBirthday();
                    MyDate b2 = e2.getBirthday();

                    //比较年
                    int minusYear = b1.getYear() - b2.getYear();
                    if (minusYear != 0){
                        return minusYear;
                    }
                    //比较月
                    int minusMonth = b1.getMonth() - b2.getMonth();
                    if (minusMonth != 0){
                        return minusMonth;
                    }
                    //比较日
                    return b1.getDay() - b2.getDay();
                }
//                return 0;
                throw new RuntimeException("传入的数据不一致!");
            }
        });

        Employee e1 = new Employee("liudehua", 55,new MyDate(1965, 5, 4));
        Employee e2 = new Employee("zhangxueyou", 43,new MyDate(1988, 5, 4));
        Employee e3 = new Employee("guofucheng", 44,new MyDate(1987, 5, 9));
        Employee e4 = new Employee("liming", 51,new MyDate(1954, 8, 12));
        Employee e5 = new Employee("liangchaowei", 21,new MyDate(1978, 12, 4));

        set.add(e1);
        set.add(e2);
        set.add(e3);
        set.add(e4);
        set.add(e5);

        Iterator iterator = set.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值