HashSet and LinkedHashSet was supposed to hold only unique values If you run the below code the duplicates values are allowed Why but if the below code is ran under the TreeSet there are no duplicates as it should be | Core Java Forum
K
Kumar Nagendra Posted on 21/10/2018
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.TreeSet;

public class HowHashSetWorksWithCustomClass {

public static void main(String[] args) {

//LinkedHashSet<Bus> hs1 = new LinkedHashSet<>();
TreeSet<Bus> hs1 = new TreeSet<>();
Bus b1 = new Bus(4.30,"Mon","10-10-2018");
Bus b2 = new Bus(2.50,"Tue","12-10-2018");
Bus b3 = new Bus(1.80,"Wed","18-10-2018");
Bus b4 = new Bus(4.30,"Mon","10-10-2018");

hs1.add(b1);
hs1.add(b2);
hs1.add(b3);
hs1.add(b4);

for(Bus b: hs1){
System.out.println("Amount is " + b.amt + " Day is " + b.day + " Date is " + b.date);
}


}

}



///////////////////This is the Bus class

import java.util.Comparator;
import java.util.Date;

public class Bus implements Comparable<Bus>{

double amt;
String day;
String date;


Bus(double a, String day, String date ){
this.amt = a;
this.day = day;
this.date = date;

}

@Override
public int compareTo(Bus o) {
if(this.amt > o.amt){
return 1;
}else if(this.amt<o.amt){
return -1;
}else{
return 0;
}
}

}

Y
Yogesh Chawla Replied on 31/10/2018

Nagendra,

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.

Do this:
hs1.add(b1);

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.


K
Kumar Nagendra Replied on 01/11/2018

Thank you for resolving the query.