0
Set<String> set2 = new HashSet<>();
String s2 = new String("rajkumar");
String s3 = new String("rajkumar");

set2.add(s3);
set2.add(s2);
System.out.println(set2.size()); //this will output 1


Person p1= new Person("rajkumar", 25);
Person p2= new Person("rajkumar", 25);
Set<Person>set= new HashSet<>();

set.add(p1);
set.add(p2);
System.out.println(set.size());//This will output 2

why is this happening. Isn't the has hashcode of a string objects should be different?

here person class is like

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
rajkumar.11
  • 313
  • 2
  • 9

4 Answers4

2

Set allows unique entries. Uniqueness is checked by equals method. Both s2 and s3 have same text hence both are equal. String class implements equals method for text comparison. On adding s3 to existing set, s3 object does not get added, instead the method returns false saying that object with same value already exists.

Person class on other hand does not implement equals and hashcode, hence the references are compared. In this case both objects get added to the set

Go through javadoc for more information.

sidgate
  • 14,650
  • 11
  • 68
  • 119
1

In Java there is String pool, which saves equal Strings in the same memory. Look at this link: https://www.journaldev.com/797/what-is-java-string-pool. if you want the same Person in once in Set you must override equals method.

Anna Tolochko
  • 1,795
  • 14
  • 20
1

The Java Set interface, java.util.Set, represents a collection of objects where each object in the Set is unique. In other words, the same object cannot occur more than once in a Java Set. source

A Hashset is backed by a hashmap

set2 is of type String. Both s2 and s3 are considered identical strings and so only one entry exists in set2

set takes objects of type Person and p1 and p2 are different objects despite the fact they have identical fields.

To test this further change the string value of s2 or s3 and also try creating equals and hashcode methods in your Person class:

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    Person person = (Person) o;
    return age == person.age &&
            Objects.equals(name, person.name);
}

@Override
public int hashCode() {
    return Objects.hash(name, age);
}
Michael W
  • 3,515
  • 8
  • 39
  • 62
0

You can look at this post: Can a set have duplicate elements?. Here are well explained how set works. But if we look at your question, your two Strings are both same(equals compare). For other hand Person object does not same. If you want Person objects works as String you should overide equals method in your class.

A. Blicharski
  • 36
  • 1
  • 6