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”運算子對此進行了檢查。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP