If you instantiate an ArrayList
the way that you've shown (you want it to be treated as Object
- this class doesn't allow iterating, classes implementing Iterable
interface provide this function), and then you need to iterate over its elements, you can cast this list
from Object
to Iterable
, that way iteration becomes available for list
:
for(A a : (Iterable<A>) list) {
// do stuff
}
or when you need an Iterator iterating over elements of the list
:
Object list = new ArrayList<A> ();
Iterator<A> it = ((Iterable<A>)list).iterator();
You might want to have a look at Java API Documentation of to read more about Iterable interface here.
Edit: This answer was edited thanks to helpful suggestions of Federico Peralta Schaffner and luk2302.