如何检查java HashSet中的重复值是否位于用户定义的类的对象内?



code

public class Society  {
private String address;
private String name;
private Integer noOfFlats;

public Society(String address, String name, int noOfFlats) {
this.address = address;
this.name = name;
this.noOfFlats = noOfFlats;
}

public class SocietySet {
Set<Society> socSet = new HashSet<>();
public void addSocToset(Society society) {
socSet.add(society);
}
public void printSocSet() {
for (Society society : socSet) {
System.out.println("[ "+society.getName()+" ,"+society.getAddress()+"             
,"+society.getNoOfFlats()+" ]");
}
}

主要方法

public static void main(String[] args) {  

SocietySet societySet = new SocietySet(); // initialized object of class

Society society1 = new Society("pune","kamalapark",15); 
Society society2 = new  Society("pune","kamalapark",15);
Society society3 = new Society("pune","dsk",50);

societySet.addSocToset(society1);
societySet.addSocToset(society2);
societySet.addSocToset(society3);
societySet.printSocSet();
}
}

它印刷了前两个社会相同的价值观。

output :
[ kamalapark ,pune ,15 ]
[ kamalapark ,pune ,15 ]
[ dsk ,pune ,50 ]

在技术上应仅打印唯一值的地方, 应该怎么做才能阻止它打印通用值?

根据定义,Set 不能包含两个具有"相等"值的对象。

你的问题是你的社会类没有任何两个社会对象相等的特定概念。

社会需要定义方法equal((和hashCode((。

将以下 2 种方法添加到您的社会类中。您必须首先使用 equals(( 和 hashcode(( 方法来验证元素是否唯一。

@Override
public boolean equals(Object obj) {
Society otherObj = (Society) obj;
return this.name.equals(otherObj .name) &&
this.noOfFlats.equals(otherObj .noOfFlats) &&
this.address.equals(otherObj .address) &&
this.hashCode() == otherObj .hashCode();
}
@Override
public int hashCode() {
return (43 + 777);
}

当您将对象放入 Hashset 时,它会使用该对象的哈希码值来确定将对象放入 Set 中的位置。但它也会将对象的哈希代码与哈希集中所有其他对象的哈希代码进行比较,如果没有匹配的哈希代码,HashSet 将假定此新对象不是重复对象。哈希集查找两个对象的匹配哈希码。一个你正在插入,一个已经在集合中 - 然后 HashSet 将调用对象的 equals(( 方法之一,以查看这些哈希代码匹配的对象是否真的相等。如果它们相等,HashSet 知道您尝试添加的对象是 Set 中某些内容的副本,因此不会发生添加。

重写此等于方法以检查对象与哈希代码的相等性。 公共布尔等于(对象 o(

您需要覆盖 equals 和 hascode 方法。

@Override
public boolean equals(Object other) {
if(!other instanceof Society) 
return false;
Society o = (Society)other;
return o.address.equals(address) && o.name.equals(name) && o.noOfFlats.equals(noOfFlats)
}
@Override
public int hashCode() 
{  
// your hascode implementation. 
} 

详细解释:https://www.geeksforgeeks.org/override-equalsobject-hashcode-method/

我相信你问题的根源不是技术上的,而是概念上的。

您的情况扭转了 Set 拒绝重复项的想法,这是真的,Sets 专门使用唯一值。但问题是这仅适用于文字,即由用户单独定义的单个值(例如"pune","kamalapark"和15,当单独添加到集合中时,作为独立元素(。

但是,当 Set 由对象而不是文字组成时,就像在代码中一样,为了使其符合唯一性,您应该使用哈希和相等方法。在这个线程中,我们已经有关于这件事的答案和评论。

希望我的解释能让你的情况更清楚。

最新更新