Cấu trúc dữ liệu Set dùng lưu giá trị duy nhất, nghĩa là không lưu giá trị trùng lặp. Khi HashSet tạo, nó triển khai HashMap nội bộ. Phần tử chèn vào HashSet bằng add. Điều này nội bộ gọi put vì HashMap đã tạo nội bộ. Do đó, Set nhận giá trị duy nhất nhờ HashMap.
HashMap chứa cặp key-value duy nhất, key-value chèn bằng put. Khi gọi put, giá trị trước liên quan với key hoặc null trả về tùy mapping có cho key hay không.
LinkedHashSetextends HashSet, nghĩa là LinkedHashSet gọi constructor HashSet bằng super.
Ví dụ
import java.util.HashSet;
public class Demo{
public static void main(String args[]){
HashSet my_hashset = new HashSet();
boolean my_b1 = my_hashset.add("only");
boolean my_b2 = my_hashset.add("sample");
boolean my_b3 = my_hashset.add("sample");
System.out.println("Giá trị boolean đầu: " + my_b1);
System.out.println("Giá trị boolean thứ hai: " + my_b2);
System.out.println("Giá trị boolean thứ ba: " + my_b3);
System.out.println(my_hashset);
}
}
Kết quả
Giá trị boolean đầu: true Giá trị boolean thứ hai: true Giá trị boolean thứ ba: false [only, sample]
Lớp Demo chứa main instance HashSet định nghĩa. Phần tử thêm vào hashset bằng add. Phần tử hiển thị trên màn hình.