Hi All,
class Demo{
private int a;
Demo(int a){
this.a = a;
}
}
public class Test{
public static void main(String[] args){
Demo d1 = new Demo(10);
Demo d2 = new Demo(20);
Set<Demo> set = new HashSet<Demo>();
set.add(d1);
set.add(d2);
System.out.println(set);
}
}
Output: [javaSE_8.Demo@15db9742, javaSE_8.Demo@6d06d69c]
I understand that the above code is printing the object reference.
public class Test{
public static void main(String[] args){
Integer i1 = 10;
Integer i2 = 20;
Set<Integer> set = new HashSet<Integer>();
set.add(i1);
set.add(i2);
System.out.println(set);
}
}
Output: [20, 10]
Where as this code prints the value itself in-spite of Integer being a class(Wrapper class) and i1, i2 being its objects.
I want to know why is this happening, or why does this difference exist.
Thank you, Suthan
Both HashSet<Demo>
and HashSet<Integer>
store references to object.
System.out.println(set)
prints the String
returned by set.toString()
method. This method calls object.toString()
for each object
in the set and concatenates them with a space.
Now because Integer.toString()
returns the actual value as a String
, you are seeing the value being printed for Integer
whereas in the case of Demo
, Demo.toString()
returns the object reference as a String
since it is the default method java.lang.Object.toString()
. You can override this method in Demo
to return the actual value as a String
.