如果 java HashSet 中的重复值位于用户定义的 class 对象中,如何检查它们?

How to check for duplicate values in java HashSet if they are inside of object of user-defined class?

代码

    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 ]

where it should technically print unique values only, what should be done to stop it from printing common values??

根据定义,集合不能包含两个具有 'equal' 个值的对象。

你的问题是你的 Society class 没有任何关于两个 Society 对象相等的特定概念。

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

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

覆盖此 equals 方法以检查对象与哈希码是否相等。 public 布尔等于(对象 o)

您将需要覆盖 equals 和 hashcode 方法。

@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/

将以下 2 种方法添加到您的 Society class.You 必须首先使用 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);
    }

我认为您的问题的根源不是技术上的,而是概念上的。

你的情况改变了 Sets 拒绝重复的想法,这是真的,Sets 专用于唯一值。但问题是这仅适用于文字,即用户单独定义的单个值(如“pune”、“kamalapark”和 15,当单独添加到集合中时,作为独立元素)。

但是,当您的代码中的 Set 由对象而不是文字组成时,为了使其符合唯一性,您应该使用 hash 和 equal 方法。在此线程中,我们已经 and 涵盖了这件事。

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