1

I want use set to remove duplicate object,the UserEntity is like:

public class UserEntity {
    String name;
    int age;
    @Override
    public String toString() {
        return "UserEntity [name=" + name + ", age=" + age + "]";
    }
    public UserEntity(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    @Override
    public boolean equals(Object o1) {
        UserEntity user=(UserEntity) o1;
        return this.age==user.age && user.name.equals(this.name);
    }
    
}

Then I create a set to add two user both called alex who`s age is 20,but there are two user in the set:

UserEntity user1 = new UserEntity("alex", 20);
UserEntity user2 = new UserEntity("alex", 20);
System.out.println(user1.equals(user2));
Set<UserEntity> set=new HashSet<>();
set.add(user1);
set.add(user2);
System.out.println(set.size());

The result is :

true
2

why the set do not remove duplicate object?

vlddlv4
  • 35
  • 4

3 Answers3

1

You broke the contract, by not overriding hashCode().

The general contract of hashCode is:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.

  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

  • It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.


And from equals():

Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

enter image description here


As you broke the rules, the HashSet can't guarantee it will work properly. Its like it's been betrayed.

This shouldn't happen in real code, because you shouldn't be violating the contract in real code

aran
  • 10,978
  • 5
  • 39
  • 69
0

When you instantiate a new object, it is exactly that, a new object, even if it contains the same data, the object hashCode is still different. You may want to look into overriding Object#hashCode as well.

NotZachery
  • 1
  • 1
  • 3
0

You are missing this. Add to your code and it will work.

public int hashCode() {
        return this.name.hashCode();
    }
Amit
  • 633
  • 6
  • 13