HashSet extends AbstractSet và implements interface Set. Nó tạo collection sử dụng hash table để lưu trữ.
Hash table lưu thông tin bằng cơ chế hashing. Nội dung thông tin của key được dùng để xác định giá trị duy nhất gọi là hash code. Hash code sau đó dùng làm index để lưu data liên kết với key. Chuyển đổi key thành hash code diễn ra tự động.
Ví dụ 1: Tạo và thêm phần tử vào HashSet
import java.util.*;
public class Demo {
public static void main(String args[]) {
HashSet<String> hashSet = new HashSet<String>();
hashSet.add("One");
hashSet.add("Two");
hashSet.add("Three");
hashSet.add("Four");
hashSet.add("Five");
hashSet.add("Six");
System.out.println("Hash set values = " + hashSet);
}
}
Kết quả
Hash set values = [Five, Six, One, Four, Two, Three]
Thứ tự không đảm bảo (hash-based), khác với LinkedHashSet (giữ thứ tự insert) hoặc TreeSet (sắp xếp).
Ví dụ 2: Xóa phần tử khỏi HashSet
import java.util.*;
public class Demo {
public static void main(String args[]) {
HashSet<String> newset = new HashSet<String>();
newset.add("Learning");
newset.add("Easy");
newset.add("Simply");
System.out.println("Values before remove: " + newset);
boolean isremoved = newset.remove("Easy");
System.out.println("Return value after remove: " + isremoved);
System.out.println("Values after remove: " + newset);
}
}
Kết quả
Values before remove: [Learning, Easy, Simply] Return value after remove: true Values after remove: [Learning, Simply]
Đặc điểm chính: Không cho phép duplicate, null được phép (tối đa 1), không thread-safe, O(1) trung bình cho add/remove/contains.