I have an ArrayList for type Room (my custom object) Defined as below
ArrayList<Room> rooms = new ArrayList<Room>();
After then adding a series of objects to the ArrayList I want to go through them all and check various things. I am not a keen user of java but I know in many other programming languages a foreach loop would be the most simple way of doing this.
After a bit of research I found the following link which suggests the code below. How does the Java 'for each' loop work?
for(Iterator<String> i = someList.iterator(); i.hasNext(); ) {
String item = i.next();
System.out.println(item);
}
But as far as I can tell this cant be used for an Arraylist of a custom object.
Can, and if so how can I implement a foreach loop for an ArrayList of a custom object? Or how could I otherwise process each item?
As of Java 8, we can use the forEach method as well as the iterator class to loop over an ArrayList.
In Java, the for-each loop is used to iterate through elements of arrays and collections (like ArrayList).
Its simply like following. ObjeMyObject objects[] = new MyObject[6]; MyObject o = Object[0]; 0 = new MyObject();
Java forEach loop It is defined in Iterable and Stream interface. It is a default method defined in the Iterable interface. Collection classes which extends Iterable interface can use forEach loop to iterate elements.
Actually the enhanced for loop should look like this
for (final Room room : rooms) {
// Here your room is available
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With