AF
Home
Tag
Submit Notes
Ask Anything
Login
Subscribe Us
A
ny
F
orum
1. Feel Free to ask and submit anything on Anyforum.in and get satisfactory answer
2. Registration is not compulsory, you can directly login via google or facebook
3. Our Experts are looking for yours ?.
Follow @anyforumin
java-collection: HashSet also returns ascending order then why TreeSet?
Set<Integer> intSet=new HashSet<Integer>();
intSet.add(1);
intSet.add(21);
intSet.add(2);
intSet.add(3);
for(Integer i:intSet){
System.out.println(i);
}
above code prints output 1, 2, 3, 21. It´s sorted in ascending order then why we go for TreeSet?
java x 211
collection x 52
Posted On :
2016-03-15 00:00:08.0
Saksham Kumar
734
339
39091
3
Answers
Hashset doesn´t guarantee the order of elements. But it calculates hashcode for objects in it. You might be having it since integers might be giving a sequential hashcode (until the capacity max is reached)
Hashset has an array of buckets. According to source code initial capacity is 16:
static final int DEFAULT_INITIAL_CAPACITY = 16;
So when you try your small integers they got placed up in order.
if you try below:
Set<Integer> intSet=new HashSet<Integer>();
intSet.add(1);
intSet.add(21);
intSet.add(2);
intSet.add(22);
intSet.add(7);
intSet.add(3);
intSet.add(4);
intSet.add(9);
intSet.add(1);
intSet.add(13);
for(Integer i:intSet){
System.out.println(i);
}
It will not maintain ascending order and insertion order either. HashSet is faster than TreeSet so if you don´t want to maintain the order then go for HashSet.
Posted On :
2016-03-15 00:09:41
Satisfied :
4 Yes
0 No
Rishi Kumar
523
1882
49150
Reply This Thread
4
Post Answer
Please Login First to Post Answer:
Login
Answer:
anyforum.in