This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I have a silly question i guess. I want to get the first element from a Set. If i use iterator i parse through the whole Set. The other way is to put the elements of the Set into ArrayList and then do .get(0) on the ArrayList.
Is there any other more efficient way to do this that is not coming in my mind right now?
I'd suggest getting an Iterator and then just call next() once. You don't need to iterate through the whole lot.
The reason the Set interface doesn't give you an obvious way of doing this is because Sets are unordered and therefore, strictly speaking, talking about the "first element of a Set" doesn't make sense.
A Set has no order, so there is not "first" or "last" item in a Set.
It is impossible at the moment to get the value at a specific index in a Set (see top answers to why).
You can however save a bit in processing by, instead of introducing the set in an Arraylist, you turn it into an Array and get the position .
Lets take a HashSet as example (using strings as content):
I would like to warn you that calling this will NOT guarantee that the String in myStringAtIndex will be the first String introduced.
I'd prefer Matthew's solution of using iterator().next(). Both creating an ArrayList and calling toArray will loop through the entire Set, whereas iterator().next() really inspects only one single element.