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:
Java Switch Statement
Reversing a Linked List in Java
A Guide to the Java ExecutorService
Java Program to Implement Sieve Of Eratosthenes
Java Program to Check Whether a Weak Link i.e. Articulation Vertex Exists in a Graph
Java Program to Implement Vector API
How to Set TLS Version in Apache HttpClient
Guide to Spring Cloud Kubernetes
Understanding Memory Leaks in Java
@Order in Spring
Removing all Nulls from a List in Java
Query Entities by Dates and Times with Spring Data JPA
Java Program to Find Basis and Dimension of a Matrix
Extract links from an HTML page
Java Program to Implement Stein GCD Algorithm
Java Program to Solve Travelling Salesman Problem for Unweighted Graph
Java Program to Generate Random Hexadecimal Byte
Java Program to Implement Shell Sort
Làm thế nào tạo instance của một class mà không gọi từ khóa new?
Getting Started with Custom Deserialization in Jackson
REST Web service: Tạo ứng dụng Java RESTful Client với Jersey Client 2.x
Apache Camel with Spring Boot
Java Program to Implement Shoelace Algorithm
Using a List of Values in a JdbcTemplate IN Clause
Introduction to Java 8 Streams
Java Program to Implement Knapsack Algorithm
Spring Data Reactive Repositories with MongoDB
Adding Shutdown Hooks for JVM Applications
Finding the Differences Between Two Lists in Java
Jackson – Unmarshall to Collection/Array
Java Program to subtract two large numbers using Linked Lists
Java 8 Collectors toMap