Is there a way to view the elements of a set by doing something like set.toArray()[i]
(i
being an integer)?
1 Answers
Convert Set
to array
If you mean to ask if a Set
can be converted into an array, and then access that array, the answer is “Yes”.
The code you show would return an object of type Object
rather than the specific type. To get the specific type, use this syntax shown in the Javadoc.
String[] stringArray = mySetOfStrings.toArray( new String[0] ) ;
String s = stringArray[ index ] ; // Where `index` is an `int` variable.
Or we could shorten that to:
String s = mySetOfStrings.toArray( new String[0] )[ index ] ;
See this code run live at IdeOne.com.
Beware: If the concrete implementation of the Set
interface does not promise a certain iteration order, then this code makes no sense. You cannot reasonably ask for the nth element of the array if you do not know the order of the elements.
Set
has no order
If you mean to ask if there is a way to get the “nth” element from a Set
, such as the second or fifth event, the answer is “No”. A Set
by definition has no order. Therefore there is no concept of a second or fifth element.
Some Set
implementations may not even have consistent, repeatable iteration order. They may iterate in one order one time, and in a different order another time.
Sorted sets
Java does offer NavigableSet
and its predecessor, SortedSet
, both extending the Set
interface.
Implementations of these interfaces keep the elements in a sorted order. When you iterate such a collection, you will encounter the elements in that sorted order.
Also, an EnumSet
iterates its elements in the order in which the enum objects are defined.
Notice how in this example code, the month of February was added third in our collection q1
, but is defined as the second object on the enum java.time.Month
. So this EnumSet
iterates with FEBRUARY
object after JANUARY
and before MARCH
.
Set< Month > q1 = EnumSet.of( Month.MARCH , Month.JANUARY , Month.FEBRUARY ) ;
Month m = q1.toArray( new Month[0] )[ 1 ] ; // Feb.
See that code run live at IdeOne.com.

- 303,325
- 100
- 852
- 1,154
-
I didn't understand the rationale behind DVing this answer. If it is because the question has been marked as a duplicate, the DVer should consider the valuable information put in this answer. – Arvind Kumar Avinash Oct 11 '21 at 17:06