Junior — Middle
How are elements retrieved from a Set collection?
sobes.tech AI
Answer from AI
In Java, the Set collection does not guarantee the order of elements and does not support access by index. To retrieve elements from a Set, an iterator or a for-each loop is usually used. For example:
Set<String> set = new HashSet<>();
set.add("apple");
set.add("banana");
for (String item : set) {
System.out.println(item);
}
You can also obtain an iterator and manually iterate through the elements:
Iterator<String> iterator = set.iterator();
while (iterator.hasNext()) {
String item = iterator.next();
System.out.println(item);
}
Thus, access to elements occurs through iteration, not by index.