10, Learn java collection sub interface: Set interface

Keywords: Java data structure linked list

1. Characteristics of stored data: unordered and unrepeatable elements

concrete:

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 according to the order of data**Hash value**Decided.

2. Non repeatability: ensure that the added elements follow the equals()Cannot return when judging true. Namely:**Only one of the same elements can be added.**

2. Element adding process: (take HashSet as an example)

We add element a to the HashSet. First, we call the hashCode() method of the class where element a is located to calculate the hash value of element A. then, we use an algorithm to calculate the storage position (i.e. index position) in the underlying array of the HashSet, and judge whether there are elements in this position of the array:

If there are no other elements at this location, the element a Added successfully. ---> Case 1

If there are other elements at this location b(Or multiple elements in the form of a linked list), the elements are compared a And elements b of hash Value:

  If hash If the values are different, the element a Added successfully. ---> Case 2

  If hash The value is the same, and then the element needs to be called a Class equals()method:

    equals()return true,element a Failed to add,

    equals()return false,Then element a Added successfully. ---> Case 3

For case 2 and case 3 of successful addition: element a The data at the specified index location already exists is 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

Conclusion: seven up and eight down

HashSet bottom layer: array + linked list structure( Premise: jdk 7)

3. Common methods:

There are no new methods defined in the Set interface, but all the methods declared in the Collection are used.

4. Common implementation classes:

  • |---- Collection interface: single column Collection, used to store objects one by one.

    • |---- Set interface: stores unordered and non repeatable data. -- >** "Collection" in high school**

      • |---- HashSet: as the main implementation class of Set interface; Thread 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; While adding data, each data also maintains two references to record the previous data and the latter data of this data; For frequent traversal operations, LinkedHashSet is more efficient than HashSet.
      • |---- TreeSet: you can sort according to the specified attributes of the added object.

5. Requirements for storage object class:

HashSet / LinkedHashSet:

Requirement 1: the class of data added to set (mainly HashSet and LinkedHashSet) must override hashCode() and equals()

Requirement 2: the rewritten hashCode() and equals() should be as consistent as possible: equal objects must have equal hash codes.

Tip for overriding two methods: using as equals()Method comparison Field,Should be used to calculate hashCode()

TreeSet:

  1. In natural sorting, the criteria for comparing whether two objects are the same is: compareTo() returns 0, not equals().

  2. In custom sorting, the criteria for comparing whether two objects are the same is: compare() returns 0, not equals().

6. Use of TreeSet

6.1 instructions:

  1. The data added to TreeSet must be objects of the same class.

  2. There are two sorting methods: natural sorting (implementing comparable interface) and custom sorting (Comparator)

6.2 common sorting methods:

  • Code example:
**Method 1: natural sorting( User Class Comparable Interface and rewritten compareTo()Method)**
@Test
public void test1(){
    TreeSet set = new TreeSet();

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

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

    //Example 2:
    set.add(new User("Tom",12));
    set.add(new User("Jerry",32));
    set.add(new User("Jim",2));
    set.add(new User("Mike",65));
    set.add(new User("Jack",33));
    set.add(new User("Jack",56));

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

**Method 2: customized sorting **
@Test
public void test2(){

    Comparator com = new Comparator() {
        //From small to large according to age
        @Override
        public int compare(Object o1, Object o2) {
            if (o1 instanceof User && o2 instanceof User){
                User user1 = (User) o1;
                User user2 = (User) o2;
                return Integer.compare(user1.getAge(),user2.getAge());
            }else {
                throw new RuntimeException("The data type entered is inconsistent!");
            }
        }
    };

    TreeSet set = new TreeSet(com);
    set.add(new User("Tom",12));
    set.add(new User("Jerry",32));
    set.add(new User("Jim",2));
    set.add(new User("Mike",65));
    set.add(new User("Mary",33));
    set.add(new User("Jack",33));
    set.add(new User("Jack",56));

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

}

Posted by DontheCat on Wed, 01 Sep 2021 14:53:11 -0700