3

Simply is it possible to create a type, in java, which can be passed into the foreach loop after the colon? And if so, how?

At first I thought I that foreach only worked for arrays, but then it came to my attention that Lists could be iterated over. My question is then is this something that the interpreter does automatically or is it possible to create classes of my own which can be used?

4 Answers 4

6

Yes, just implement the Iterable interface.

From http://docs.oracle.com/javase/6/docs/api/java/lang/Iterable.html:

Implementing this interface allows an object to be the target of the "foreach" statement.

Sign up to request clarification or add additional context in comments.

Comments

2

Yes, it is possible. You have to implement the Iterable interface and you can use it in the enhanced for loop.

As the documentation says:

Implementing this interface allows an object to be the target of the "foreach" statement.

Comments

1

To have this functionality you can implement Iterable interface. You need to implement your own iterator() method. Then, you can use the foreach loop.

Comments

1

Yes. As it says in the Java Language Specification, you need to implement the Iterable interface. If you do, instances of your class can be used in an enhanced for loop.

Iterable is a very, very simple interface: It requires that you have an iterator method that returns an Iterator<T> instance.

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.