Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach loop in java for a custom object list

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?

like image 843
mr.user1065741 Avatar asked Nov 22 '12 22:11

mr.user1065741


People also ask

Can you use a forEach loop on an ArrayList?

As of Java 8, we can use the forEach method as well as the iterator class to loop over an ArrayList.

Can we use forEach loop for list in Java?

In Java, the for-each loop is used to iterate through elements of arrays and collections (like ArrayList).

How do you write a loop for an object in Java?

Its simply like following. ObjeMyObject objects[] = new MyObject[6]; MyObject o = Object[0]; 0 = new MyObject();

Which interface is required for forEach method on collection object?

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.


1 Answers

Actually the enhanced for loop should look like this

for (final Room room : rooms) {
          // Here your room is available
}
like image 130
ShyJ Avatar answered Sep 18 '22 10:09

ShyJ