Java Set Interview Questions
Ques: So to see the output of this program you think that in hashset there is no duplicate element is allowed then how here age is 1 for all and still storing the value.
Sol: Hash set just check the reference id of newly created object not the content of the object and with new key word we created 3 Employe object so all the referene a re different so all object are unique so that’s why its able to store the data into hashset.
So how to stop storing the same age data in my program we have to do something.
- We have to override hashCode method and for which attribute you want to check on which is repeating like in my case age is duplicate.
- Now override of equals method.
Example
package com.collection.programs;
import java.util.HashSet;
class Employee{
int age;
String name;
public Employee(int age, String name) {
super();
this.age = age;
this.name = name;
}
}
Try it »
Ques: Now question is when comparable is there then why comparator comes into picture.
Sol: Because in Comparable you can write logic for 1 attribute means you write the logic of comparing any one attribute if you are comparing on age then you cannot write compare logic for name attribute and if we write in increasing order then you cannot write decreasing order means only 1 a time but in comparator in another class we create the logic of sorting and use whenever we need. And who is writing code for object creation he has to write code for comparing as well but in comparator 1 can make object creation and one who is best on sorting. These are the drawbacks of comparable.
Example
package com.collection.programs;
import java.util.Comparator;
import java.util.TreeSet;
class NameComparison implements Comparator{
public int compare(Object o1,Object o2) {
Employe e1 = (Employe)o1;
Employe e2 = (Employe)o2;
return e1.name.compareTo(e2.name);
}
}
class AgeComparison implements Comparator{
public int compare(Object o1,Object o2) {
Employe e1 = (Employe)o1;
Employe e2 = (Employe)o2;
if(e1.age< e2.age)
return 1;
else if(e1.age>e2.age)
return -1;
else
return 0;
}
}
Try it »