Java access index for each cycle

I read that

for (int i1 : A) { } 

better than

  for (int i1=0; i1 < A.length; i++) { } 

but if I want to access the index value in the first, is there any average value or should I use only the second.

+4
source share
7 answers

Wikipedia states:

foreach loops usually do not support an explicit counter: they essentially say โ€œdo this with everything in this set , rather than โ€œ do this x times . โ€ This avoids the errors that occur in turn and makes code reading easier.

If you want to use the index, it is better to use the latest version.

if I want to access the index value in the first, is there any average value

Yes, you can

 int index = 0; for (int i1 : A) { // Your logic // index++; } 

but then again, not recommended. if you need an index in Enahanced for loop , rethink your logic.

Java recommends an enahanced for loop: Source (see last line on page)

+3
source

No no. You just need to declare a variable. Better just use the traditional one in this case.

0
source

Use this or best use the second option

  int count = 0; for (int i1 : A) { print count; count ++; } 
0
source

As mentioned above, also look at this similar question. Is there a way to access the iteration counter in a Java loop for each loop?

0
source

you must use the second. Another option is to use the List as collection.
List list = Arrays.asList(int a[]); list.get(int index);

0
source

First you specify the code, look through all the objects / objects in the collection A, But the last code says to go through the index from 0 to n, n=>size of A

In the normal case, both will work, and what to choose is usually based on which API for the loop you can use.

In your first code, the HashMap array is running or not populating. Say you have this data structure.

 A = [1,2,3,NULL,NULL,4,NULL,5] 

In your first case, you can only scroll through existing values. But in the latter case, you should skip all the elements.

Also, an unordered or clearly defined data structure, such as Maps, may have a method that ensures that you go through all the elements, but not in a clearly defined order.

0
source

No, you canโ€™t. For everyone, it is considered the best (to indicate your question), because it does not have the variable count. This means that, from the point of view of the programmer, less space remains. The programmer does not need to retrieve data. Java does this for you with everyone.

I use for-each every time I don't need a counter variable. If I need an account, then I have to use the old style for the loop.

0
source

Source: https://habr.com/ru/post/1442910/


All Articles