The
elements in TreeSet are sorted according to specified Comparator.
If no Comparator is specified, elements will be placed according to
their natural ascending order.
class
MyComparator
implements
Comparator<Student>
{
@Override
public
int
compare(Student
s1, Student s2){
if(s1.id == s2.id)
{
return 0;
}
else
{
return s2.perc_Of_Marks_Obtained - s1.perc_Of_Marks_Obtained;
}
}
}
//Instantiating
MyComparator
MyComparator
comparator = new
MyComparator();//Creating TreeSet with 'MyComparator' as Comparator.
TreeSet<Student> set = new TreeSet<Student>(comparator);
Order
Of Elements
|
HashSet
doesn’t maintain any order of elements.
|
LinkedHashSet
maintains insertion order of elements. i.e elements are placed as
they are inserted.
|
TreeSet
orders the elements according to supplied Comparator. If no
comparator is supplied, elements will be placed in their natural
ascending order.
|
Performance
|
HashSet
gives better performance than the LinkedHashSet and TreeSet.
|
The
performance of LinkedHashSet is between HashSet and TreeSet. It’s
performance is almost similar to HashSet. But slightly in the
slower side as it also maintains LinkedList internally to maintain
the insertion order of elements.
|
TreeSet
gives less performance than the HashSet and LinkedHashSet as it
has to sort the elements after each insertion and removal
operations.
|
Collections
is an utility class in java.util package. It consists of only static
methods which are used to operate on objects of type
Collection.
Collections.max()
|
This
method returns maximum element in the specified collection.
|
Collections.sort()
|
This
method sorts the specified collection.
|
Collections.copy()
|
This
method copies all elements from one collection to another
collection.
|
Collections.reverse()
|
This
method reverses the order of elements in the specified collection.
|
No comments:
Post a Comment