Java basics (Set collection)

I. Overview

Set has the same interface as Collection, but the behavior is different. Set does not save duplicate elements, and the elements in Set interface are out of order.

What you need to know in this section:

What is a hash table?

The bottom of the hash table also uses the array mechanism. The objects are stored in the array. The location of these objects is relatively special. When these objects are stored in the array, they will be calculated according to the unique data of these objects and the corresponding algorithm (hashCode). The position of this object in the array, and then store this object in the array. Such an array is called a hash array, that is, a hash table.

When storing elements in the hash table, the hashCode method in the Object class is called . Since any object is a subclass of the Object class, any object has this method. It should be noted here that if the hashCode method of the two objects calculates the same result, this phenomenon is called hash conflict. At this time, the equals method of the object will be called to compare whether the two objects are the same object. Then the second object will not be stored in the hash table, if the return is false, this value will be stored in the hash table.

To ensure that the uniqueness of Set elements is actually determined based on the object's hashCode and equals methods. If we store a custom object in the collection, then to ensure its uniqueness, we must repeat the hashCode and equals methods to establish a comparison method that belongs to the current object.

Example: comparison of set and list

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class demo_set无序 {
    public static void main(String[] args) {
        List<String> list=new ArrayList<>();
        list.add("aaa");
        list.add("ccc");
        list.add("aaa");
        list.add("bbb");
        //不保存重复的元素且无序
        Set set=new HashSet();
        set.add("ccc");
        set.add("aaa");
        set.add("bbb");
        set.add("aaa");
        System.out.println(list);
        System.out.println(set);
    }
}

operation result:

Second, HashSet stores custom objects

When using HashSet to store custom objects, we have to override hashCode () and equals () methods

because:

       When calling the add () method of HashSet, it will first determine whether hashCode () is the same,

       If it is the same, it will judge the equals () again. If the equals () is the same, then it will not be saved.

For example, two people in the class have the same name and age, but they must be saved.

Examples:

import java.util.HashSet;

public class demo_set添加对象 {
    public static void main(String[] args) {
        HashSet<Student> hashSet=new HashSet<>();
        hashSet.add(new Student("yyy",21));
        hashSet.add((new Student("wtc",21)));
        //添加重复元素
        hashSet.add((new Student("wtc",21)));
        System.out.println(hashSet);
    }
}
class Student{
    String name;
    int age;

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

    @Override
    public boolean equals(Object o) {
        return super.equals(o);
    }

    @Override
    public int hashCode() {
        return this.name.hashCode()+age;
    }

    @Override
    public String toString() {
        return "姓名:" + name  +
                " 年龄:" + age;
    }
}

operation result:

3. Exercises

           1. Get 10 non-repeating random numbers between 1-20

import java.util.HashSet;
import java.util.Random;

public class demo_获取10个不重复随机数 {
    public static void main(String[] args) {
        HashSet hashSet=new HashSet();
        Random r=new Random();
        while(hashSet.size()<10){
            //范围1-20
            int i=r.nextInt(20)+1;
            hashSet.add(i);
        }
        System.out.println(hashSet);
    }
}

operation result:

 Four, TreeSet interface

Features: 1. Elements are ordered
           2. Cannot store duplicate elements

Store custom objects: Need to tell it what to sort by 

                               Need to implement the interface: Compareble

                               Abstract method to implement the interface: compareTo  

                                         Write the sorting rules in it

                                            Three values ​​can be returned in compareTo

                                            * 1. greater than 0 * 2. less than 0 * 3. equal to 0 * 

Examples:

import java.util.TreeSet;

public class demo_TreeSet {
    public static void main(String[] args) {
        TreeSet treeSet=new TreeSet();
        treeSet.add("aaa");
        treeSet.add("ddd");
        treeSet.add("bbb");
        treeSet.add("ccc");
        treeSet.add("aaa");
        System.out.println(treeSet);

        TreeSet<Students> treeSet1=new TreeSet<>();
        treeSet1.add(new Students("yyy",20));
        treeSet1.add(new Students("wtc",23));
        treeSet1.add(new Students("wt",22));
        treeSet1.add(new Students("wtc",20));

        System.out.println(treeSet1);
    }
}
class Students implements Comparable<Students>{
    String name;
    int age;

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

    @Override
    public int compareTo(Students o) {
        //解决年龄相同的问题,按年龄排序
        int i=this.age-o.age;
        return i==0?this.name.compareTo(o.name):i;
    }

    @Override
    public String toString() {
        return "Students{" +
                "姓名:" + name +
                " 年龄:" + age +
                '}';
    }
}

operation result:

Fifth, the sorting comparator is passed in through the construction method

Solve the problem: you can't make changes in the object class to implement the interface

Examples:


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

public class demo_构造方法传入比较器 {
    public static void main(String[] args) {
        //第一种写法
        Comparator comparator=new Comparator<Person>(){
            @Override
            public int compare(Person o1, Person o2) {
                //实现按年龄排序
                int i=o1.age-o2.age;
                return i==0?o1.name.compareTo(o2.name):i;
            }
        };
        TreeSet<Person> treeSet=new TreeSet<>(comparator);

        /**第二种写法
         *         TreeSet<Person> treeSet=new TreeSet<>(ew Comparator<Person>(){
         *             @Override
         *             public int compare(Person o1, Person o2) {
         *                 //实现按年龄排序
         *                 int i=o1.age-o2.age;
         *                 return i==0?o1.name.compareTo(o2.name):i;
         *             }
         *         });
         */

        treeSet.add(new Person("YYY",18));
        treeSet.add(new Person("wtc",21));
        treeSet.add(new Person("wt1",21));

        System.out.println(treeSet);
    }
}
class Person{
    String name;
    int age;

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

    @Override
    public String toString() {
        return "Person{" +
                "姓名:" + name + '\'' +
                " 年龄:" + age +
                '}';
    }
}

operation result:

 

 

 

Published 75 original articles · praised 164 · 110,000 views

Guess you like

Origin blog.csdn.net/qq_41679818/article/details/96729011