Java Foundation (Collection)

Posted by bitt3n on Wed, 09 Mar 2022 12:37:12 +0100

1, Overview of collection framework

  • 1. Sets and arrays are structures that store multiple data, referred to as Java containers for short
       note: storage at this time mainly refers to memory storage, and does not involve persistent storage (. txt,.jpg,.avi, database)

  • 2. Characteristics of array in storing multiple data:
      > once initialized, its len gt h is determined.
      > once the array is defined, the type of its elements is determined. Only data of the specified type can be manipulated.
       for example: String arr[];int[] arr1;Object[] arr2;
      disadvantages:
         length cannot be modified
         the methods provided in the array are very limited, which is very inconvenient for adding, deleting, inserting data and other operations, and the efficiency of colleagues is not high
         obtain the number of actual elements in the array. There are no ready-made attributes or methods available in the array
         characteristics of data storage: orderly and repeatable. For unnecessary and non repeatable requirements, they cannot be met

2, Collection framework

  | - Collection interface: single column Collection, which is used to store objects one by one
List interface: stores ordered and repeatable data. – > Dynamic array
      |—ArraysList,LinkedList,Vector
    | - Set interface: stores unordered and non repeatable data. – > High school "collection"
      |—HashSet,LinkedHashSet,TreeSet
  | - Map interface: a double column set used to store a pair of key value data -- > high school function y = f(x)
    |—HashMap,LinkHashMap,TreeMap,Hashtable,Properties

3, Use of methods in the Collection interface

   when adding data obj to the object of the implementation class of the Collection interface, the class of obj is required to override equals()

public class CollectionTest {

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

        //add(Object e): add element e to the collection coll
        coll.add("AA");
        coll.add("BB");
        coll.add("123");//Automatic packing
        coll.add(new Date());

        //Get the number of elements added by size():
        System.out.println(coll.size());//4

        //addAll(Collection coll1): adds the elements in the coll1 collection to the current collection
        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: clear collection elements
        coll.clear();

        //isEmpty(): judge whether the current collection is empty
        System.out.println(coll.isEmpty());//False / / true after clear
    }

    @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): judge whether the current set contains enough obj
        //When judging, it will call equals() of the class where the obj object is located
        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)));//Compare the equals method of the class where the object is located. false
        //When the equals method is overridden, it becomes true

        //containsAll(Collection coll1): judge whether all elements in the formal parameter coll1 exist in the current collection
        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): remove the obj element from the current collection and call equals for matching
        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): removes all elements in coll1 from the current collection
        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);

        //Retain all (collection coll1): intersection: get the intersection of the current collection and coll1 collection and return it to the current collection
//        Collection coll1 = Arrays.asList(123, 456, 789);
//        coll.retainAll(coll1);
//        System.out.println(coll);//[123, 456]

        //equals(Object obj): to return true, the elements of the current set and the parameter set must be the same
        Collection coll3 = new ArrayList();//ArrayList ordered
        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
        //After 123 / 456 exchange sequence, 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(): returns the hash value of the current object
        System.out.println(coll.hashCode());//701070075

        //Collection -- > array: 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

        //Extension: array -- > collection: call the static method asList() of the Arrays class
        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 considers that the array has only one element

        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(): returns an instance of the iterator interface for traversing collection elements. Put it in iteratortest Testing in 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);
//    }
}

The traversal operation of collection elements uses the Iterator iterator interface

  • 1. Internal methods: hasNext(), next()
  • 2. Every time the collection object calls the iterator() method, it gets a new iteration and object. The default cursor is before the first element of the collection
  • 3. Remove () is defined internally, which can delete the elements in the collection during traversal. This method is different from the direct call to remove() from the collection
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();

        //Mode 1:
//        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

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

        //Method 3: Recommended
        //hasNext() determines whether there is a next element
        while(iterator.hasNext()){
            //next(): ① move the pointer down ② return the elements at the collection position after moving down
            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);

        //Error mode 1:
//        Iterator iterator = coll.iterator();
//        while((iterator.next()) != null){
//            //next(): ① move the pointer down ② return the elements at the collection position after moving down
//            System.out.println(iterator.next());
//        }
        //456
        //Tom
        //java.util.NoSuchElementException

        //Error mode 2:
        //Every time a collection object calls the iterator() method, it gets a new iteration and object. The default cursor is before the first element of the collection
        while(coll.iterator().hasNext()){
            System.out.println(coll.iterator().next());
        }
        //123
        //123
        //123
        //...

    }

    //Test remove() in Iterator
    @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);

        //Test remove() in Iterator
        //If next() has not been called or the remove method has been called since the next method was last called,
        //Calling remove again will report 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
            }
        }
        //Traversal set
        Iterator iterator1 = coll.iterator();
        while (iterator1.hasNext()){
            System.out.println(iterator1.next());
        }
    }
}

jdk 5.0 adds a foreach loop to traverse sets and arrays

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 (type of element in the collection local variable: collection object)
        //The iterator is still called internally
        for (Object obj : coll){
            System.out.println(obj);
        }
    }

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

        //For (type of element in array, local variable: array object)
        for (int i : arr){
            System.out.println(i);
        }
    }

    //Exercises
    @Test
    public void test3(){
        String[] arr = new String[]{"MM", "MM", "MM"};
        //Method 1: ordinary for assignment
//        for (int i = 0;i < arr.length; i++){
//            arr[i] = "GG";
//        }
        //GG
        //GG
        //GG

        //Mode 2: enhance for loop
        //Reassign a value of S and modify s without changing the elements in the original array
        for (String s : arr){
            s = "GG";
        }
        //MM
        //MM
        //MM

        for (int i = 0; i < arr.length; i++){
            System.out.println(arr[i]);
        }
    }
}
  • 1. | - Collection interface: single column Collection, used to store objects one by one
      | - List interface: stores ordered and repeatable data. – > Dynamic array
        | - ArraysList: as the main implementation class of the List interface, the thread is unsafe and the efficiency is high; The underlying layer uses Object[] elementData storage
        | - LinkedList: for frequent insertion and deletion operations, the efficiency of using this type is higher than that of ArrayList; The bottom layer uses two-way linked list storage
        | - Vector: as an ancient implementation class of List interface, it is thread safe and inefficient; The underlying layer uses Object[] elementData storage
  • 2. Source code analysis of ArrayList:
      2.1jdk7
        ArrayList list = new ArrayList();// The bottom layer creates an Object [] array elementData with a length of 10
        list.add(123);//elementData[0] = new Integer(123);
        ...
        list.add(11);// If the capacity of the underlying elementData array is insufficient due to this addition, the capacity will be expanded.
         by default, the capacity expansion is 1.5 times of the original capacity. At the same time, the array in the original array needs to be copied to the new array

   conclusion: it is recommended to use constructors with parameters in development: ArrayList = new ArrayList (int capacity);

   changes of ArrayList in 2.2jdk 8:
    ArrayList list = new ArrayList();// The underlying Object [] array elementData is initialized to {}, and there is no array with length of 10
    list.add(123);// When add is called for the first time, the bottom layer creates an array with a length of 10 and returns the data to elementData[0] for 123 days
     . . .
     subsequent addition and capacity expansion operations are consistent with jdk 7
   2.3 summary: JKD 7 -- > hungry Han style
       JDK 8 -- > lazy (delaying array creation to save memory)

  • 3. Source code analysis of linklist:
      LinkList list = new LinkList(); The first and last attributes of Node type are declared internally, and the default value is null
      list.add(123);// Encapsulate 123 into Node and create Node object.

  • 4. Source code analysis of vector: when creating objects through the Vector() constructor in jdk 7 and jdk 8, the underlying layer creates an array with a length of 10,
      in terms of capacity expansion, the default capacity expansion is twice the length of the original array.

  • 5. Common methods in list interface
      interview question: what are the similarities and differences among ArraysList, LinkedList and Vector?
       same: the three classes implement the List interface, and the characteristics of storing data are the same: storing orderly and repeatable data

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): inserts an ele element at the index position
        list.add(1, "bb");
        System.out.println(list);//Move the bottom layer back one by one / / 123, bb, 456, AA, Person{name='Tom', age=20}, 456]

        //boolean addAll(int index, Collection eles): add all elements in eles from the index position
        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): get the element at the specified index position
        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): returns the position where obj first appears in the collection. If it does not exist, - 1 is returned
        int index = list.indexOf(456);
        System.out.println(index);//1 (index value)

        //int lastIndexOf(Object obj): returns the last occurrence of obj in the collection. If it does not exist, - 1 is returned
        System.out.println(list.lastIndexOf(456));//4

        //Object remove(int index): removes the element at the specified index position and returns this element
        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): sets the element of the specified index position to ele
        list.set(1, "cc");
        System.out.println(list);//[456, cc, Person{name='Tom', age=20}, 456]

        //List subList(int fromIndex, int toIndex): returns the left closed and open subset from fromIndex to 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 interface: single column Collection, used to store objects one by one
  | - Set interface: stores unordered and unrepeatable data. – > High school "collection"
    | - HashSet: as the main implementation class of Set interface -- > thread is unsafe; null values can be stored
      | - LinkedHashSet: as a subclass of HashSet, when traversing its internal data, it can be traversed in the order of addition
               LinkedHashSet is more efficient than HashSet for frequent traversal operations
    | - TreeSet: you can sort according to the specified attributes of the added object

  • 1. There is no new method defined in the set interface, but all the methods declared in the Collection are used

  • 2. Requirements: the class of data added to Set must override hashCode() and equals()
          the rewritten hashCode() and equals() are as consistent as possible: equal objects must have equal hash codes

1, Set: stores unordered and non repeatable data
  take HashSet as an example:
  1. Disorder: not equal to randomness. The stored data is not added in the order of array index in the underlying array, but determined according to the hash value of the data.

  2. Non repeatability: ensure that the added element cannot return true when judged according to equals(). That is, only one element can be added to the same element.

2, The process of adding elements: HashSet take as an example

   add element a to the HashSet. First call the hashCode() method of the class where element a is located to calculate the hash value of A,
   this hash value then calculates the storage location (i.e. index location) in the underlying array of HashSet through some algorithm,
   judge whether there are elements in this position of the array:
     if there are no other elements in this position, element a is added successfully. -- > Case 1
     if there are other elements b in this position (or there are multiple elements in the form of linked list), compare the hash value of a and element b:
        if the hash values are different, element a is added successfully. -- > Situation 2
        if the hash values are the same, you need to call the equals() method of the class where element a is located:
          equals() returns true, adding element a failed
          equals() returns false, then element a is added successfully. -- > Situation 3

     for case 2 and case 3 of successful addition: element a and the data already existing at the specified index position are stored in a linked list.
     jdk 7: put element a into the array and point to the original element
     jdk 8: the original element is in the array and points to element a
    summary: seven up and eight down

     HashSet bottom layer: array + linked list structure

@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
    }

    //Use of LinkedHashSet
    //LinkedHashSet is a subclass of HashSet. While adding data, each data also maintains two references to record the data before and after the secondary data
    //Advantages: for frequent traversal operations, LinkedHashSet is more efficient than 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;
    }

    //Sort by name and age
    @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("Input type mismatch");
        }
    }
}
  • 1. The data added to TreeSet must be objects of the same class.

  • 2. Two sorting methods: natural sorting (implementing Comparable interface) and customized sorting (Comparator)

  • 3. In natural sorting, the standard for comparing whether two objects are the same is: compareTo() returns 0. No longer equals()

  • 4. In custom sorting, the standard for comparing whether two objects are the same is: compare() returns 0. No longer equals()

public class TreeSetTest {

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

        //You cannot add objects of different classes
//        set.add(123);
//        set.add(456);
//        set.add("AA");
//        set.add(new User("Tom", 22));

        //Example 1:
//        set.add(34);
//        set.add(-34);
//        set.add(24);
//        set.add(11);
//        set.add(8);
        //-34
        //8
        //11
        //24
        //34

        //Example 2:
//        set.add("cc");
//        set.add("aa");
//        set.add("bb");
//        set.add("ff");

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

        //Example 3
        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());
        }
        //After rewriting the Comparable method in User, it will not be rewritten and an error will be reported
        //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() {
            //Sorted by age
            @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("The data types entered do not match");
                }
            }
        };

        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());
        }

    }
}

practice
Define an Employee class
This class includes: private member variables name, age and birthday, where birthday is the object of MyDate class;
And define getter and setter methods for each attribute
And override the toString method to output name, age and 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 +
                '}';
    }

    //In the order of names
    @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("The data type passed in is inconsistent");
    }
}

The MyDate class contains:
private member variables year, month and day: and define getter and setter methods for each attribute:

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 +
                '}';
    }
}

Create five objects of this class and put them into the TreeSet collection
Sort the elements in the collection in the following two ways and traverse the output:

1. Use Employee to implement the Comparable interface and sort by name
2. When creating a TreeSet, pass in the Comparable object and sort it according to the order of birthday date

public class EmployeeTest{

    //Question 1: use natural sorting
    @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());
        }

    }

    //Question 2: according to the order of birthday dates
    @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();

                    //Comparative year
                    int minusYear = b1.getYear() - b2.getYear();
                    if (minusYear != 0){
                        return minusYear;
                    }
                    //Comparison month
                    int minusMonth = b1.getMonth() - b2.getMonth();
                    if (minusMonth != 0){
                        return minusMonth;
                    }
                    //Comparison day
                    return b1.getDay() - b2.getDay();
                }
//                return 0;
                throw new RuntimeException("The incoming data is inconsistent!");
            }
        });

        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());
        }
    }
}

Topics: Java