Junior — Middle
Is it possible to use a For-Each loop to iterate over an object that does not implement the collection interface or is not an array?
sobes.tech AI
Answer from AI
In Java, the for-each (enhanced for) loop can only be used for objects that implement the Iterable interface or are arrays. If an object does not implement Iterable and is not an array, then you cannot use for-each directly.
For example, the following code will work:
List<String> list = Arrays.asList("a", "b", "c");
for (String s : list) {
System.out.println(s);
}
But if you have an object that does not implement Iterable, you need to use other methods for iteration, such as a traditional index-based loop (if it is an array) or obtaining an iterator, if possible.
If you want to use for-each for your own class, you can implement the Iterable interface and define the iterator() method.