HashSet 在 Java 中的重要性


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”運算子對此進行了檢查。

更新時間:23-11-2023

354 次瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始學習
廣告
© . All rights reserved.