posted 14 years ago
As for "more efficient" you would have to time it, if you have an operating system which can actually time the tiny, tiny, interval that code would take to run. And of course that's supposing you meant "minimum execution time" when you said "efficiency" and not something else.
However by using TreeSet your resulting code does something different than what your original code did. The original code put the numbers into the array in the order they were received. A TreeSet stores them in numerical order. That's not the same. Use a LinkedHashSet if you want it to keep the entries in the order they were inserted in.
As for "better", you're halfway there. You still have the confusing fancy footwork for the loop index, only it's more confusing now. If you want to repeat trying to add an entry to the set until the set has 6 entries, then write code which does that in a straightforward way: