Storing data in sorted manner in a HashSet

166 views Asked by At

From what I read, HashSet stores data in a unsorted manner. However I was given this question . (I don't want anyone to solve it)

Write a program to keep car details in a HashSet with sorted manner on the based of car name using comparator. Also calculate which car have maximum and minimum speed And average speed of all car.car class structure could be like.Also consider exception scenarios

(car is a class that has a element name)
I am confused now. Is it possible the question is slightly wrong? If so can anyone help me in figuring the correct question?

2

There are 2 answers

0
shruti1810 On BEST ANSWER

The question appears to be slightly wrong. It should be :

Write a program to keep car details in a Set with sorted manner on the based of car name using comparator. Also calculate which car have maximum and minimum speed And average speed of all car.car class structure could be like.Also consider exception scenarios

Because, only TreeSet has a constructor which accepts Comparator. You cannot use Comparator with HashSet.

2
Serge Ballesta On

I suppose that what is asked is to use a LinkedHashSet. Is is a subclass of HashSet as per first requirement, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order).

If you cannot make sure that car details will be added in the right order, you should use dedicated subclass of HashSet, using also a LinkedList for the order, but controlling insertion order. But as the question does not expose performance requirement, it is hard to say if this is really the required implementation.