Java Hashset.contains() produces mysterious result

后端 未结 3 933
忘了有多久
忘了有多久 2020-12-09 17:41

I don\'t usually code in Java, but recently I started not having a choice. I might have some major misunderstanding of how to properly use HashSet. So it might be possible s

3条回答
  •  无人及你
    2020-12-09 18:09

    When you are adding objects to a set it internally calls equals and hashCode methods. You have to override these two methods. For example I have taken one bean class with name,id,designation, then created and added an employee object.

    HashSet set = new HashSet();
    Employee employee = new Employee();
    employee.setId(1);
    employee.setName("jagadeesh");
    employee.setDesignation("programmer");
    set.add(employee);
    Employee employee2 = new Employee();
    employee2.setId(1);
    employee2.setName("jagadeesh");
    employee2.setDesignation("programmer");
    set.add(employee2);
    

    set.add() calls internally the equals and hashCode methods. So you have to override these two methods in your bean class.

    @Override
    public int hashCode(){
        StringBuffer buffer = new StringBuffer();
        buffer.append(this.name);
        buffer.append(this.id);
        buffer.append(this.designation);
        return buffer.toString().hashCode();
    }
    @Override
    public boolean equals(Object object){
        if (object == null) return false;
        if (object == this) return true;
        if (this.getClass() != object.getClass())return false;
        Employee employee = (Employee)object;
        if(this.hashCode()== employee.hashCode())return true;
       return false;
    }   
    

    Here we are overriding equals() and hashCode(). When you add an object to the HashSet method it internally iterates all objects and calls the equals method. Hence we overrid hashCode, it compares every objects hashCode with its current hashCode and returns true if both are equal, else it returns false.

提交回复
热议问题