Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Question:Output of below Java program

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?

like image 483
Abhishek Jain Avatar asked Dec 12 '22 22:12

Abhishek Jain


2 Answers

There are two unequal instances of abc1 (note that it doesn't override equals or hashCode) and one string in the set. Let's look at the four add calls:

hs.add(a1);

Originally the set is empty - so obviously this will add the value.

hs.add(a2);

This will also add the value to the set, because they are distinct objects and the default implementation of equals/hashCode is basically reference identity.

hs.add(s1);

This will add the value to the set as the string isn't equal to either of the current values (which aren't strings).

hs.add(s2);

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.

like image 150
Jon Skeet Avatar answered Dec 23 '22 11:12

Jon Skeet


Because the set structure (notice how your hashmap is backed by a set) does not allows two equal objects to be stored. That's how sets behave.

Now, You may be fooled to think that both a1 and a2 are equal, but if they don't override equals or hashCode then for Java they are not equal. However with your strings s1 and s2, they are indeed equal because the String implementation already overrides the equals and hashCode methods. Try doing s1.equals(s2) and you'll get a true as result. If you do a1.equals(a2) you'll get false.

At the end, your hashset contains a1, a2 and s1.

You extended your question, so to answer that...

s1 and s2 are not referring to the same object, they are two different String objects but both represent the same set of characters. Since they are not the same object, System.out.println(s1 == s2) prints false. They are equal(), but not the same object.

like image 21
Cesar Avatar answered Dec 23 '22 12:12

Cesar