public class abc1 {
private String s;
public abc1(String s){this.s=s;}
public static void main(String args[])
{
HashSet<Object> hs=new HashSet<Object>();
abc1 a1= new abc1("abc");
abc1 a2= new abc1("abc");
String s1= new String("abc");
String s2= new String("abc");
hs.add(a1);
hs.add(a2);
hs.add(s1);
hs.add(s2);
System.out.println(hs.size());
}
}
Why above program output is 3?
Edit
Seeing below comments I am extending my question:
System.out.println (s1 == s2);
Are s1 and s2 refering to same object? If then the above statement should print true but its output is false.
Are they are similar in terms of hashcode but still differnt?
There are two unequal instances of
abc1(note that it doesn’t overrideequalsorhashCode) and one string in the set. Let’s look at the fouraddcalls:Originally the set is empty – so obviously this will add the value.
This will also add the value to the set, because they are distinct objects and the default implementation of
equals/hashCodeis basically reference identity.This will add the value to the set as the string isn’t equal to either of the current values (which aren’t strings).
This will not add anything to the set, as the second string is equal to the first. (String overrides
equals/hashCode.)The result is a set with three items in.