JAVA basics--Set collection

Chapter 4 Set Interface

java.util.SetLike the interface java.util.List, the interface also inherits from the Collectioninterface. It Collectionis basically the same as the method in the interface. It does not Collectionexpand the function of the interface, but Collectionit is more strict than the interface. ListDifferent from the interface, the Setelements in the interface are out of order, and some rules are used to ensure that the stored elements do not appear duplicated.

SetCollections have multiple subclasses, and here we introduce these java.util.HashSettwo java.util.LinkedHashSetcollections.

Tips: The way to extract elements from the Set collection can be: iterator, enhanced for.

4.1 Introduction to HashSet Collection

java.util.HashSetIt is Setan implementation class of the interface, and the elements it stores are not repeatable , and the elements are all out of order (that is, the access order is inconsistent). java.util.HashSetThe underlying implementation is actually a java.util.HashMapsupport, since we haven't learned it yet, let's understand it first.

HashSetIt is based on the hash value of the object to determine the storage location of the element in the collection, so it has good access and search performance. The way to guarantee the uniqueness of elements depends on the : hashCodeand equalsmethod.

Let's first use the Set collection storage, look at the phenomenon, and then explain the principle:

public class HashSetDemo {
    
    
    public static void main(String[] args) {
    
    
        //创建 Set集合
        HashSet<String>  set = new HashSet<String>();

        //添加元素
        set.add(new String("cba"));
        set.add("abc");
        set.add("bac"); 
        set.add("cba");  
        //遍历
        for (String name : set) {
    
    
            System.out.println(name);
        }
    }
}

The output is as follows, indicating that duplicate elements cannot be stored in the collection:

cba
abc
bac

Tips: According to the results, we found that only one string "cba" is stored, that is to say, the repeated element set collection is not stored.

2.2 The structure of the HashSet collection storing data (hash table)

What is a hash table?

Before JDK1.8 , the bottom layer of the hash table was implemented by an array + linked list, that is, a linked list was used to handle conflicts, and linked lists with the same hash value were all stored in a linked list. However, when there are many elements in a bucket, that is, there are many elements with the same hash value, the efficiency of sequentially searching by key value is low. In JDK1.8, hash table storage is implemented by array + linked list + red-black tree. When the length of the linked list exceeds the threshold (8), the linked list is converted into a red-black tree, which greatly reduces the search time.

Simply put, the hash table is implemented by an array + linked list + red-black tree (JDK1.8 added the red-black tree part).

All in all, JDK1.8 introduced the red-black tree to optimize the performance of HashMap to a great extent, so for us, the uniqueness of the HashSet collection elements is actually determined according to the hashCode and equals method of the object. If we store a custom object in the collection, then to ensure its uniqueness, we must override the hashCode and equals methods to establish a comparison method belonging to the current object.

2.3 HashSet stores custom type elements

When storing custom type elements in HashSet, you need to rewrite the hashCode and equals methods in the object and establish your own comparison method to ensure that the objects in the HashSet collection are unique

Create a custom Student class

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;
        return age == student.age &&
               Objects.equals(name, student.name);
    }

    @Override
    public int hashCode() {
    
    
        return Objects.hash(name, age);
    }
}
public class HashSetDemo2 {
    
    
    public static void main(String[] args) {
    
    
        //创建集合对象   该集合中存储 Student类型对象
        HashSet<Student> stuSet = new HashSet<Student>();
        //存储 
        Student stu = new Student("于谦", 43);
        stuSet.add(stu);
        stuSet.add(new Student("郭德纲", 44));
        stuSet.add(new Student("于谦", 43));
        stuSet.add(new Student("郭麒麟", 23));
        stuSet.add(stu);

        for (Student stu2 : stuSet) {
    
    
            System.out.println(stu2);
        }
    }
}
执行结果:
Student [name=郭德纲, age=44]
Student [name=于谦, age=43]
Student [name=郭麒麟, age=23]

2.3 LinkedHashSet

We know that HashSet guarantees that the elements are unique, but the elements are stored in no order, so we need to ensure order, what should we do?

There is a subclass under HashSet java.util.LinkedHashSet, which is a data storage structure combined with a linked list and a hash table.

The demo code is as follows:

public class LinkedHashSetDemo {
    
    
	public static void main(String[] args) {
    
    
		Set<String> set = new LinkedHashSet<String>();
		set.add("bbb");
		set.add("aaa");
		set.add("abc");
		set.add("bbc");
        Iterator<String> it = set.iterator();
		while (it.hasNext()) {
    
    
			System.out.println(it.next());
		}
	}
}
结果:
  bbb
  aaa
  abc
  bbc

Guess you like

Origin blog.csdn.net/qq_44660367/article/details/108107179