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:
CyclicBarrier in Java
Java Program to Implement Euclid GCD Algorithm
Java Program to Implement ConcurrentLinkedQueue API
Java Byte Array to InputStream
Java Program to Find SSSP (Single Source Shortest Path) in DAG (Directed Acyclic Graphs)
Interface trong Java 8 – Default method và Static method
MyBatis with Spring
Java Program to Implement Dijkstra’s Algorithm using Queue
Java Program to Implement Binomial Tree
Java Program to Implement SimpeBindings API
Java Program to Implement Sieve Of Sundaram
Java Program to Represent Graph Using Adjacency List
Java Concurrency Interview Questions and Answers
Spring MVC Content Negotiation
Luồng Daemon (Daemon Thread) trong Java
Jackson – JsonMappingException (No serializer found for class)
Java Program to Implement Circular Singly Linked List
Java Program to Find kth Smallest Element by the Method of Partitioning the Array
Write/Read cookies using HTTP and Read a file from the internet
How to Round a Number to N Decimal Places in Java
Converting a Stack Trace to a String in Java
Câu lệnh điều khiển vòng lặp trong Java (break, continue)
@Before vs @BeforeClass vs @BeforeEach vs @BeforeAll
Spring – Injecting Collections
Java Program to Implement RenderingHints API
Java – String to Reader
Collect a Java Stream to an Immutable Collection
Spring Data MongoDB Transactions
Getting a File’s Mime Type in Java
Custom Cascading in Spring Data MongoDB
Java Program to Implement Depth-limited Search
Using the Not Operator in If Conditions in Java