Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

자바에서 HashSet의 중요성

<시간/>

HashSet은 해싱을 사용하여 데이터를 조작합니다. 예를 들어 보겠습니다 -

예시

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")));
   }
}

출력

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

'Demo' 클래스는 최종 문자열과 생성자를 포함합니다. 객체가 특정 클래스의 인스턴스인지 확인하는 equals 함수가 정의됩니다. 인스턴스이면 true를 반환하고 그렇지 않으면 객체를 클래스로 캐스팅하고 'equals' 함수를 사용하여 검사합니다. 메인 함수에서 새로운 Set이 생성되고 인스턴스가 생성됩니다. 'instanceof' 연산자를 사용하는지 확인합니다.