Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How a List can be iterated as if it is an array

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

like image 824
Adam Pahlevi Baihaqi Avatar asked Nov 18 '25 13:11

Adam Pahlevi Baihaqi


2 Answers

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.

like image 198
morgano Avatar answered Nov 21 '25 03:11

morgano


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
} 
like image 22
Ankur Lathi Avatar answered Nov 21 '25 02:11

Ankur Lathi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!