In java there are several ways to iterate.
Both are known as for
and foreach
; the latter is used for collections of objects (Arrays, lists and other data structures) .
In this case, the for (Integer numero: primos)
is known as foreach
in other programming languages. This can also be written as for(int i = 0; i < primos.size(); i++)
. Both do exactly the same, the difference is that in the second, to obtain an object within the ArrayList<Integer>
is done with the method get(i)
, while in the first (foreach)
and directly extract the object where you are iterating, it is saved in numero
, and automatically when it passes to the next item, numbers will be the next item.
The foreach syntax in java, or the for for iterating collections of objects, is as follows:
for (Class x : a){codigo aqui...}
Where:
-
Class
is the class to which the collection of objects in the list to iterate belongs, in your case Integer
, since the list will save objects of this class.
-
x
is the variable to which each item of the list will be assigned (This will be seen later in more detail as it works)
-
a
is the name of the list or collection, which must be declared and instantiated.
A simple example, let's say we want to print 5 numbers in a list, and we have 5 elements in a ArrayList
:
5 | 4 | 9 | 5 | 7
-
With the for
normal: for(int i = 0; i < primos.size(); i++)
, to print them, we said that to obtain an object with this method we must use the get(i)
method that is a member of ArrayList<>
, therefore it is as follows:
for(int i = 0; i < primos.size(); i++){
System.out.println(primos.get(i));
}
In this way we make sure that for every change of the for counter, the next element of the list of primes is printed, and so on until the same list ends.
-
With the foreach: for (Integer numero: primos)
, it is not necessary to do this, since with the foreach
, or with this type of for, at the end of the iteration, numero
takes the next object from the list, if not there is more then the for
ends automatically.
Using the previous example of printing and arranging numbers, it looks like this:
for (Integer numero: primos){
System.out.println(numero);
}
With this simple code the same previous result is achieved.
Now, the use already depends on your needs, the foreach is used when the search is linear, that is, one by one, when you want to scroll the list through all the elements as ordered in the ArrayList < > . If you want to scroll through the list in an unordered manner, or for example, from the middle of the list to the end, the normal for, not the foreach, is used.
I hope it has served you.