Trong các bài viết trước, tôi đã giới thiệu với các bạn HashMap và HashSet. Trong bài này, tôi sẽ so sánh sự giống nhau, khác nhau của 2 collection này.
1. Giống nhau của HashMap và HashSet
- Cả hai cấu trúc dữ liệu không duy trì bất kỳ thứ tự cho các phần tử truyền vào.
- Cả hai đều sử dụng phương thức hashCode () và equals () để duy trì tính duy nhất của dữ liệu.
- Cả hai cung cấp cho hiệu suất thời gian là hằng số cho các thao tác chèn (add/ put) và loại bỏ (remove).
- Cả hai đều không đồng bộ (non-synchronized).
2. Khác nhau của HashMap và HashSet
| HashSet | HashMap |
| HashSet cài đặt (implement) Set interface. | HashMap cài đặt (implement) Map interface. |
| HashSet lưu trữ dữ liệu dưới dạng các đối tượng (object). | HashMap lưu trữ dữ liệu dưới dạng cặp khóa-giá trị (key-value). |
| Bên trong HashSet sử dụng HashMap. | Bên trong HashMap sử dụng một mảng đối tượng Entry<K, V>. |
| HashSet không cho phép các phần tử trùng lặp. | HashMap không cho phép các khóa (key) trùng lặp, nhưng cho phép các giá trị (value) trùng lặp. |
| HashSet chỉ cho phép một phần tử null. | HashMap cho phép một khóa (key) null và nhiều giá trị (value) null. |
| Thao tác chèn (insert/add) chỉ yêu cầu một đối tượng. | Thao tác chèn (put) yêu cầu hai đối tượng, khóa và giá trị (key-value). |
| HashSet hơi chậm hơn HashMap. | HashMap nhanh hơn một chút so với HashSet. |
| Sử dụng HashSet khi bạn cần duy nhất dữ liệu (object). | Sử dụng HashSet khi bạn cần duy nhất khóa (key). |
Related posts:
Spring Boot - Admin Server
Java Program to Implement Rope
Spring Security Basic Authentication
Java 8 Streams peek() API
A Guide to Spring Boot Admin
“Stream has already been operated upon or closed” Exception in Java
Remove the First Element from a List
Java Program to Implement Kosaraju Algorithm
Primitive Type Streams in Java 8
Java Program to Find Median of Elements where Elements are Stored in 2 Different Arrays
Serialize Only Fields that meet a Custom Criteria with Jackson
LinkedHashSet trong Java hoạt động như thế nào?
Hướng dẫn Java Design Pattern – Template Method
Spring Boot - Service Components
Java Program to Implement Quick Sort with Given Complexity Constraint
Java InputStream to String
Java – Byte Array to Reader
Java Program to Implement Traveling Salesman Problem using Nearest neighbour Algorithm
Deploy a Spring Boot WAR into a Tomcat Server
Build a REST API with Spring and Java Config
Quick Guide to the Java StringTokenizer
Setting a Request Timeout for a Spring REST API
Examine the internal DNS cache
Java Program to Implement Circular Singly Linked List
Java Program to Implement Sorting of Less than 100 Numbers in O(n) Complexity
Java Program to Implement Hamiltonian Cycle Algorithm
Assert an Exception is Thrown in JUnit 4 and 5
Transaction Propagation and Isolation in Spring @Transactional
The Spring @Controller and @RestController Annotations
Spring WebFlux Filters
Interface trong Java 8 – Default method và Static method
Using JWT with Spring Security OAuth