HashSet trong java

1. Giới thiệu

Lớp HashSet trong Java kế thừa AbstractSet và triển khai Set Interface. Nó tạo một collection mà sử dụng một hash table để lưu giữ.

Một hash table lưu giữ thông tin bởi sử dụng một kỹ thuật được gọi là hashing (băm). Trong hashing, nội dung mang tính thông tin của một key được sử dụng để quyết định một value duy nhất, được gọi là hash code của nó.

Hash code sau đó được sử dụng như là index, tại đó dữ liệu mà liên kết với key được lưu giữ. Phép biến đổi của key vào trong hash code của nó được thực hiện tự động.

Các điểm quan trọng về lớp HashSet trong java là:

  • HashSet chỉ chứa các phần tử duy nhất, không chấp nhận 2 phần tử trùng nhau.
  • HashSet lưu trữ các phần tử bằng cách sử dụng một cơ chế được gọi là hashing (băm).
  • HashSet không đảm bảo thứ tự được thêm vào.
  • HashSet cho phép chứa phần tử NULL.

2. Hierarchy của lớp HashSet

hashset-hierarchy

Lớp java.util.HashSet được định nghĩa như sau:

public class HashSet<E> extends AbstractSet<E>
        implements Set<E>, Cloneable, java.io.Serializable {
    static final long serialVersionUID = -5024744406713321676L;
 
    private transient HashMap<E,Object> map;
 
    private static final Object PRESENT = new Object();
 
    public HashSet() {
        map = new HashMap<>();
    }
}

3. Các phương thức khởi tạo (constructor) của lớp HashSet

  • HashSet(): khởi tạo một danh sách mảng trống.
  • HashSet(Collection c): khởi tạo một danh sách với các phần tử của collection c.

4. Các phương thức (method) của lớp HashSet

Xem thêm các phương thức của Set ở bài viết Set Interface trong java.

5. Ví dụ minh họa

5.1. Ví dụ sử dụng HashSet với kiểu dữ liệu cơ bản (Wrapper)

import java.util.HashSet;
import java.util.Set;
 
public class HashSetExample2 {
    public static final int NUM_OF_ELEMENT = 5;
 
    public static void main(String[] args) {
        // Create set
        Set<String> set = new HashSet<>();
        set.add("Item01");
        set.add("Item02");
        set.add("Item03");
        set.add("Item04");
        set.add("Item05");
        set.add("Item02");
        set.add("Item03");
 
        // Show set through for-each
        for (String item : set) {
            System.out.print(item + " ");
        }
    }
}

Kết quả thực thi chương trình trên:

Item04 Item03 Item02 Item01 Item05 

5.2. Ví dụ sử dụng LinkedList với kiểu do người dùng tự định nghĩa (Object)

import java.util.HashSet;
import java.util.Set;
 
class Student {
    private int id;
    private String name;
 
    public Student(int id, String name) {
        this.id = id;
        this.name = name;
    }
 
    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + "]";
    }
}
 
public class HashSetExample {
    public static final int NUM_OF_ELEMENT = 5;
 
    public static void main(String[] args) {
        // Create list
        Set<Student> students = new HashSet<>();
        Student student1 = new Student(1, "myname1");
        Student student2 = new Student(2, "myname2");
        Student student3 = new Student(3, "myname3");
        Student student4 = new Student(4, "myname4");
        Student student5 = new Student(5, "myname5");
        students.add(student1);
        students.add(student2);
        students.add(student3);
        students.add(student4);
        students.add(student5);
        students.add(student2);
        students.add(student3);
 
        // Show set student
        for (Student student : students) {
            System.out.println(student);
        }
    }
}

Kết quả thực thi chương trình trên:

Student [id=1, name=myname1]
Student [id=4, name=myname4]
Student [id=5, name=myname5]
Student [id=3, name=myname3]
Student [id=2, name=myname2]

Related posts:

How to Iterate Over a Stream With Indices
Kiểu dữ liệu Ngày Giờ (Date Time) trong java
Retrieve User Information in Spring Security
Spring Data JPA and Null Parameters
Java Program to Generate All Subsets of a Given Set in the Gray Code Order
Encode/Decode to/from Base64
Java 8 and Infinite Streams
Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java
Spring Data Reactive Repositories with MongoDB
Java Program to Remove the Edges in a Given Cyclic Graph such that its Linear Extension can be Found
Java Program to Implement Levenshtein Distance Computing Algorithm
A Guide to the Java LinkedList
Documenting a Spring REST API Using OpenAPI 3.0
Guide to java.util.concurrent.Locks
Spring Cloud Bus
Java Program to Check if a Matrix is Invertible
Java Program to Find k Numbers Closest to Median of S, Where S is a Set of n Numbers
Java Program to Evaluate an Expression using Stacks
Java Program to Implement Ternary Tree
Java Map With Case-Insensitive Keys
Java Program to Implement Hash Tables Chaining with Binary Trees
Java Program to Implement Stein GCD Algorithm
Java 8 Streams peek() API
Chương trình Java đầu tiên
Tính đa hình (Polymorphism) trong Java
Java Program to Perform Preorder Non-Recursive Traversal of a Given Binary Tree
Control Structures in Java
JWT – Token-based Authentication trong Jersey 2.x
Java Program to Find the Shortest Path Between Two Vertices Using Dijkstra’s Algorithm
The Registration Process With Spring Security
Handle EML file with JavaMail
How to Convert List to Map in Java

2 Trackbacks / Pingbacks

  1. So sánh HashSet, LinkedHashSet và TreeSet trong Java – Blog của VietMX
  2. HashSet trong Java hoạt động như thế nào? – Blog của VietMX

Comments are closed.