Is there any alternative in Java that may correspond to foreach{} available in other languages such as C# or VB or the languages alike? It may sometimes, in some very specific circumstances be very useful and almost mandatory.
Can the following while(){} loop in Java be replaced with a foreach loop or some other concepts that may exist in Java and correspond to foreach?
public class Demo
{
public static void main(String[] args)
{
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("A");
arrayList.add("B");
arrayList.add("C");
arrayList.add("D");
arrayList.add("E");
Iterator<String>it=arrayList.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}
}
I went on a long search on Google but I couldn’t.
If an object implements
Iterableor it is an array, then you can use the enhanced for-each loop (introduced in Java 5.0)If your example, you can do
Technically your example was using a non-parameterized list, so you would use