Set set correlation

Set

1.1 Set overview and features

Set set features:

  • A collection that does not contain duplicate elements
  • There is no indexed method, so you can't use a normal for loop to traverse

Set set exercise

  • Store string and traverse
package com.fun01;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * @author 23389.
 * @date 2021/6/20.
 */

/*
Set Collection features:

- A collection that does not contain duplicate elements
- There is no indexed method, so you can't use a normal for loop to traverse

HashSet There is no guarantee of the iterative order of the set
 */

public class SetDemo {
    public static void main(String[] args){
//        Create collection object
        Set<String> set = new HashSet<String>();

        //Add element
        set.add("hello");
        set.add("world");
        set.add("java");
        //Does not contain duplicate elements
        set.add("world");

        //ergodic
        for(String s : set){
            System.out.println(s);
        }

         Iterator<String> it = set.iterator();
         while(it.hasNext()){
             String s = it.next();
             System.out.println(s);
         }
    }
}

1.2 hash value

Hash value: it is a value of int type calculated by JDK according to the address, string or number of the object

There is a method in the Object class to get the hash value of the Object

  • public int hashCode(): returns the hash code value of the object

Hash value characteristics of object

  • The hashCode() method is called multiple times for the same object, and the returned hash value is the same
  • By default, the hash values of different objects are different. Rewriting the hashCode() method can make the hash values of different objects the same

1.3 HashSet set overview and features

HashSet set features:

  • The underlying data set is a hash table
  • There is no guarantee for the iterative order of the set, that is, the stored and extracted elements are not consistent
  • There is no indexed method, so this uses a normal for loop to traverse
  • Because it is a set set, it does not contain a collection of duplicate elements

HashSet set exercise

  • Store string and traverse
package com.fun03;

import java.util.HashSet;
import java.util.Iterator;

/**
 * @author 23389.
 * @date 2021/6/21.
 */
public class HashSetDemo {
    public static void main(String[] args){
        
        //Create collection object
        HashSet<String> hset = new HashSet<String>();

        //Add element
        hset.add("hello");
        hset.add("world");
        hset.add("java");

        System.out.println(hset);

        //Enhanced for loop traversal
        for(String s : hset){
            System.out.println(s);
        }

        //Iterator traversal
        Iterator<String> it = hset.iterator();
        while(it.hasNext()){
            String s = it.next();
            System.out.println(s);
        }
    }
}

1.4 source code analysis of HashSet set to ensure element uniqueness

The process of adding an element to the HashSet collection

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-ry74rryv-1627886013863) (C: \ users \ 23389 \ appdata \ roaming \ typora user images \ image-20210621143740111. PNG)]

1.5 hash table of common data structures

Hashtable

  • Before JDK8, the bottom layer was implemented by array + linked list, which can be said to be an array of element linked list
  • After JDK8, when the length is long, the bottom layer is optimized

1.6 case: the HashSet set stores student objects and traverses them

Requirements: create a collection of student objects and store three student objects. The program is to traverse the collection on the console.

Idea:

① Define student classes

② Create a HashSet collection object

③ Create student object

④ Add students to collection

⑤ Traversal collection (enhanced for loop mode)

⑥ Override the euqals() and hashSet() methods to generate automatically

package com.fun04;

/**
 * @author 23389.
 * @date 2021/6/22.
 */
public class Student {
    private String name;
    private int age;

    public Student() {
    }

    public Student(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 boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Student student = (Student) o;

        if (age != student.age) return false;
        return name != null ? name.equals(student.name) : student.name == null;
    }

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

package com.fun04;

import java.util.HashSet;

/**
 * @author 23389.
 * @date 2021/6/22.
 */
public class HashSetDemo {
    public static void main(String[] args) {
        //Create collection object
        HashSet<Student> hs = new HashSet<Student>();

        //Create student object
        Student s1 = new Student("Zhang San",18);
        Student s2 = new Student("Li Si",21);
        Student s3 = new Student("Wang Wu",20);
        Student s4 = new Student("Wang Wu",20);

        //Add element to collection
        hs.add(s1);
        hs.add(s2);
        hs.add(s3);
        hs.add(s4);

        //ergodic
        for(Student s : hs){
            System.out.println(s.getName() + "," + s.getAge());
        }

    }
}

1.7 LinkedHashSet set overview and features

LinkedhaseSet set features

  • The Set interface implemented by hash table and linked list has predictable iteration order
  • The order of elements is guaranteed by the linked list, that is, the storage and extraction order of elements are consistent
  • The hash table ensures that the elements are unique, that is, duplicate elements

LinkedHashSet set exercise

  • Store string traversal
package com.fun05;

import java.util.LinkedHashSet;

/**
 * @author 23389.
 * @date 2021/6/22.
 */
public class LinkedHashSetDemo {
    public static void main(String[] args){
        LinkedHashSet<String> linkedHashSet = new LinkedHashSet<String>();

        linkedHashSet.add("hello");
        linkedHashSet.add("world");
        linkedHashSet.add("java");
        linkedHashSet.add("happy");
        linkedHashSet.add("hello");

        for(String s : linkedHashSet){
            System.out.println(s);
        }
    }
}

1.8 TreeSet set overview and features

TreeSet set features

  • Elements are ordered. The order here does not refer to the order of storage and retrieval, but is sorted according to certain rules. The specific sorting method depends on the construction method

    TreeSet(): sort according to the natural sorting of elements

    TreeSet(Comparator comparatot): sort according to the specified comparator

  • There is no indexed method, so you cannot use a normal for loop

  • Because it is a Set collection, it does not contain duplicate elements

TreeSet stores integers and traverses

package com.fun06;


import java.util.TreeSet;

/**
 * @author 23389.
 * @date 2021/6/22.
 */
public class TreeSetDemo {
    public static void main(String[] args){

        //Create collection object
        TreeSet<Integer>  ts = new TreeSet<Integer>();

        //Add element
        ts.add(1);
        ts.add(5);
        ts.add(2);
        ts.add(5);

        //ergodic

        for(int a : ts){
            System.out.println(a);
        }

    }
}

1.9 use of natural sorting Comparable

  • Store and traverse the student object, create a TreeSet collection, and use the parameterless construction method
  • Requirements: sort according to the age from small to large. If the age is the same, sort according to the alphabetical order of the name

Conclusion:

  • The TreeSet collection is used to store custom objects, and the parameterless construction method uses natural sorting to sort the collection
  • Natural sorting is to make the class to which the element belongs implement the CompareTo(T o) method
  • When rewriting methods, be sure to note that the collation must be written according to the required primary and secondary conditions

1.10 use of Comparator sorting Comparator

  • Store the student object and traverse it, create a TreeSet collection, and use the construction method with parameters
  • Requirements: sort according to the age from small to large. If the age is the same, sort according to the alphabetical order of the name
package com.fun07;

import java.util.Comparator;
import java.util.TreeSet;

/**
 * @author 23389.
 * @date 2021/6/22.
 */

/*
- Store the student object and traverse it, create a TreeSet collection, and use the construction method with parameters
- Requirements: sort according to the age from small to large. If the age is the same, sort according to the alphabetical order of the name
 */

public class TreeSetDemo {
    public static void main(String[] args){
        //Create collection object
        TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {

            @Override
            public int compare(Student s1, Student s2) {
                //this.age - s.age
                //s1,s2
                int num = s1.getAge() - s2.getAge();
                int num2 = num == 0 ? s1.getName().compareTo(s2.getName()) : num;
                return num2;
            }
        });

        //Create student object
        Student s1 = new Student("shiqiaorui",21);
        Student s2 = new Student("wangzhongzhong",20);
        Student s3 = new Student("liuyuanhnang",19);
        Student s4 = new Student("liushuang",20);

        //Add student object to collection
        ts.add(s1);
        ts.add(s2);
        ts.add(s3);
        ts.add(s4);

        //Traversal set

        for(Student s : ts){
            System.out.println(s.getName() + "," + s.getAge());
        }



    }
}

Conclusion:

  • When storing custom objects with the TreeSet collection, the parameterized constructor uses comparator sorting to sort the elements
  • Comparator sorting is to let the collection construction method receive the implementation class object of comparator and rewrite the compare(T o,T o2) method
  • When rewriting a method, be sure to note that the collation must be written according to the required primary and secondary conditions

1.11 cases: ranking of achievements

Requirements: use TreeSet set to store multiple student information (name, Chinese score, mathematics score), and traverse the set

Requirements: appear from high to low according to the total score

① Define student objects

② Create a TreeSet collection object and sort by comparator sorting

③ Create student object

④ Add student object to collection

⑤ Traversal set

package com.fun08;

import java.util.Comparator;
import java.util.TreeSet;

/**
 * @author 23389.
 * @date 2021/6/22.
 */

/*
Requirements: use TreeSet set to store multiple student information (name, Chinese score, mathematics score), and traverse the set

​          Requirements: appear from high to low according to the total score

①Define student objects

②Create a TreeSet collection object and sort by comparator sorting

③Create student object

④Add student object to collection

⑤Traversal set
 */

public class TreeSetTest {
    public static void main(String[] args){
        TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
//                int num = (s2.getChinese() + s2.getMath() - s1.getChinese() - s1.getMath());
                int num = s2.getSum() - s1.getSum();
                int num2 = num == 0 ? s1.getChinese() - s2.getChinese() : num;
                int num3 = num2 == 0 ? s1.getName().compareTo(s2.getName()) : num2;
                return num3;
            }
        });

        //Create student object
        
        Student s1 = new Student("Zhang San",85,90);
        Student s2 = new Student("Wang Wu",90,90);
        Student s3 = new Student("Li Si",85,85);
        
        //Student s4 = new Student("Li Si", 85,85);
        Student s4 = new Student("Zhao Yun",85,85);

//        Add element to collection
        ts.add(s1);
        ts.add(s2);
        ts.add(s3);
        ts.add(s4);

        //ergodic
        for(Student s : ts){
            System.out.println(s.getName() + "," + s.getChinese() + "," + s.getMath());
        }

    }
}

1.12 non repeating random number

Requirements: write a program to obtain 10 random numbers between 1 and 20. It is required that the random numbers cannot be repeated and output on the console

Idea:

① Create Set collection object

② Create random number object

③ Judge whether the length of the set is less than 10

Yes: generate a random number and add it to the collection

Go back to ③ and continue

④ Traversal set

package com.fun09;

import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;

/**
 * @author 23389.
 * @date 2021/6/22.
 */

/*
Requirements: write a program to obtain 10 random numbers between 1 and 20. It is required that the random numbers cannot be repeated and output on the console



Idea:

①Create Set collection object

②Create random number object

③Judge whether the length of the set is less than 10

​     Yes: generate a random number and add it to the collection

​     Go back to ③ and continue

④Traversal set


 */

public class SetDemo {
    public static void main(String[] args){
        //Create collection object
//        Set<Integer> set = new HashSet<Integer>();
        Set<Integer> set = new TreeSet<Integer>();
        //Create Random object

        Random r = new Random();

        //Judge whether the length of the set is less than 10
        while(set.size() < 10){
            //Generate a random number and add it to the collection
            int a = r.nextInt(20) + 1;
            set.add(a);
        }

        //Traversal set
        for(Integer b : set){
            System.out.println(b);
        }


    }

}

Sort by TreeSet

HashSet no sort

 Yes: generate a random number and add it to the collection

Go back to ③ and continue

④ Traversal set

*/

public class SetDemo {
public static void main(String[] args){
//Create collection object
// Set set = new HashSet();
Set set = new TreeSet();
//Create Random object

    Random r = new Random();

    //Judge whether the length of the set is less than 10
    while(set.size() < 10){
        //Generate a random number and add it to the collection
        int a = r.nextInt(20) + 1;
        set.add(a);
    }

    //Traversal set
    for(Integer b : set){
        System.out.println(b);
    }


}

}



TreeSet Sort

HashSet No sort

Keywords: set

Added by shaitand on Mon, 03 Jan 2022 06:31:01 +0200