InstructorYogesh Chawla Replied on 31/10/2018
You are right. HashSet and LinkedHashSet are to hold only unique data which they are holding in this example also but this statement would look more relevant if we add the same Bus class object twice in this example.
and you will see b1 object will not show twice in the output.
If you are saying that by making bus class attributes - Amount, Day and Date same - the objects will also become same then remember these are non static variables and each and every object has got its own copy of non static variables so that is different.(Check Module 5 for that) and
If you want to make same object for same data then we need to adopt singleton design pattern methodology(check module 29 for that)
Ultimately Collections Framework is for store and manipulation of objects. Inside the objects, the values could be same or different. Making a same
object, that is a different concept all together.
And you are right for TreeSet since you are implementing Comparable interface, we have mentioned how to sort the bus class object on the basis of Amount so the data is getting printed in the ascending order of Amount only and since it is the set implementation class so only the unique data will come. Basically with TreeSet, we can individually traverse each and every attribute of a class object so that's the reason we are able to eradicate duplicate object from the TreeSet object itself, that's how TreeSet works and that's the reason working of TreeSet and TreeMap is different from all other Set and Map interface implementation classes.
Thank you for resolving the query.