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