Computer >> Máy Tính >  >> Lập trình >> Java

Tầm quan trọng của HashSet trong Java

HashSet sử dụng Hashing để thao tác dữ liệu. Hãy để chúng tôi xem một 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("Added a new element to the set");
      System.out.println("Does the set contain a new instance of the object? ");
      System.out.println(my_set.contains(new Demo("Jo", "Gold")));
   }
}

Đầu ra

Added a new element to the set
Does the set contain a new instance of the object?
false

Lớp ‘Demo’ chứa một chuỗi cuối cùng và một phương thức khởi tạo. Một hàm bằng được định nghĩa để kiểm tra xem một đối tượng có phải là một thể hiện của một lớp cụ thể hay không. Nó trả về true nếu nó là một cá thể khác truyền đối tượng vào lớp và kiểm tra bằng cách sử dụng hàm 'equals'. Trong hàm chính, một Tập hợp mới được tạo và một thể hiện được tạo. Điều này được kiểm tra để sử dụng toán tử ‘instanceof’.