11

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?

2
  • Did you try it? Of course it works with custom objects. Try it out. Commented Nov 22, 2012 at 22:03
  • 1
    google search "java foreach" brings up the following page: docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html A bit of research? Took me 2 seconds. Commented Nov 22, 2012 at 22:06

5 Answers 5

39

Actually the enhanced for loop should look like this

for (final Room room : rooms) {
          // Here your room is available
}
Sign up to request clarification or add additional context in comments.

4 Comments

in the code above what is the 'final' for? The example below doesn't seem to have this.
Using final keyword is considered a good practice whenever you're using a variable which holds a constant value or a reference (like in your case) which should not change. In this for loop it prevents the code inside it to accidently assign a different Room to the room local variable.
@ShyJ It doesn't really add anything though. Assigning room does no harm, and making room final doesn't prevent any harm that could be done by mutating a room.
@Cubic Well, without final you could actually have a room = new Room () statement in the loop body and operate on a completely different room.
12

You can also use Java 8 stream API and do the same thing in one line.

If you want to print any specific property then use this syntax:

ArrayList<Room> rooms = new ArrayList<>();
rooms.forEach(room -> System.out.println(room.getName()));

OR

ArrayList<Room> rooms = new ArrayList<>();
rooms.forEach(room -> {
    // here room is available
});

if you want to print all the properties of Java object then use this:

ArrayList<Room> rooms = new ArrayList<>();
rooms.forEach(System.out::println);

Comments

6
for(Room room : rooms) {
  //room contains an element of rooms
}

3 Comments

What is the difference between this sample and the code in the other answer that includes the word 'final'?
If a variable is final, it means you cant change its value.
So that while iterating you are not allowed to update its value.
2

You can fix your example with the iterator pattern by changing the parametrization of the class:

List<Room> rooms = new ArrayList<Room>();
rooms.add(room1);
rooms.add(room2);
for(Iterator<Room> i = rooms.iterator(); i.hasNext(); ) {
  String item = i.next();
  System.out.println(item);
}

or much simpler way:

List<Room> rooms = new ArrayList<Room>();
rooms.add(room1);
rooms.add(room2);
for(Room room : rooms) {
  System.out.println(room);
}

Comments

0

If this code fails to operate on every item in the list, it must be because something is throwing an exception before you have completed the list; the likeliest candidate is the method called "insertOrThrow". You could wrap that call in a try-catch structure to handle the exception for whichever items are failing without exiting the loop and the method prematurely.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.