HashSet dùng Hashing thao tác dữ liệu. Hãy xem ví dụ:
Ví dụ
import java.util.*;
public class Demo{
private final String f_str, l_str;
public Demo(String f_str, String l_str){
this.f_str = f_str;
this.l_str = l_str;
}
public boolean equals(Object o){
if (o instanceof Demo)
return true;
Demo n = (Demo)o;
return n.f_str.equals(f_str) && n.l_str.equals(l_str);
}
public static void main(String[] args){
Set<Demo> my_set = new HashSet<Demo>();
my_set.add(new Demo("Joe", "Goldberg"));
System.out.println("Đã thêm phần tử mới vào set");
System.out.println("Set có chứa instance mới của đối tượng? ");
System.out.println(my_set.contains(new Demo("Jo", "Gold")));
}
}
Kết quả
Đã thêm phần tử mới vào set Set có chứa instance mới của đối tượng? false
Lớp Demo chứa string final và constructor. Hàm equals kiểm tra object có phải instance lớp cụ thể. Trả về true nếu instance, ngược lại ép kiểu và kiểm tra bằng equals. Trong main, Set mới tạo, instance tạo. Kiểm tra bằng instanceof.