I have seen code like this:
List<String> listOfStrings = new ArrayList<>();
listOfStrings.add("A");
listOfStrings.add("B");
for(String txt: listOfStrings) {
System.out.println(txt);
}
I have not seen the internal code of ArrayList or its interface, as I don't have the jar need to be attached so as to I can see the source.
Can anyone explain how is this possible?
okay okay. I updated the question.... I want to make it clear like: can I create my own data structure and then through-some-special-internal-code perhaps, user also can use for each loop on my own data structure
This for clause does this:
for(T item: Iterable<T>)
the first part (T item) is for the element that belongs to any class that implements Iterable (the second part))
It's actually not an ArrayList feature, but you can do it with any Iterable class.
Because internally it is converted into Iterator for collections.
This for-each loop,
for (type var : coll) {
body-of-loop
}
will be converted into following form:
for (Iterator<type> iter = coll.iterator(); iter.hasNext(); ) {
type var = iter.next();
body-of-loop
}
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