More than 3000 questions in repository. There are more than 900 unanswered questions. Click here and help us by providing the answer. Have a video suggestion. Click Correct / Improve and please let us know.
Ans. 1. HashSet doesnt maintain its elements in any specific order and is all random whereas TreeSet maintains elements in natural order 9 order defined by the equals method of TreeSet element type )
2. TreeSet doesnt allow null elements whereas HashMap does.
3. As TreeSet orders elements and is hence insertion is comparatively slower.
4. HashSet performs basic operations like add(), remove(), contains(), size() etc. in a constant size time. A TreeSet performs these operations at the order of log(n) time.
5. HashMap in Java internally backs a HashSet. A NavigableMap backs a TreeSet internally.
Help us improve. Please let us know the company, where you were asked this question :
If we add Enum constants to a sorted collection ( Treemap , TreeSet ), What will be the order in which they will be maintained ?
Sorted Collection wont maintain them in any order.
Insertion Order
Order in which constants are declared.
Natural Sorting Order.
enums are intrinsically ..
private
public
static
final
Enums cannot be declared ..
private
public
static
final
Q6. What will be the output of the following code ?
enum Day {
MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY,SUNDAY
}
public class BuggyBread1{
public static void main (String args[]) {
Set mySet = new HashSet();
mySet.add(Day.SATURDAY);
mySet.add(Day.WEDNESDAY);
mySet.add(Day.FRIDAY);
mySet.add(Day.WEDNESDAY);
for(Day d: mySet){
System.out.println(d);
}
}
}
Ans. FRIDAY , SATURDAY and WEDNESDAY will be printed but the order cannot be determined.
Only one FRIDAY will be printed as Set doesn't allow duplicates. Order cannot be determined as HashSet doesn't maintain elements in a particular order.
Help us improve. Please let us know the company, where you were asked this question :