Is Java syntax for iterating in arrays allocate memory?

I am programming for a device with a memory limit. Therefore, I want to avoid allocating any memory.

Obviously, an iteration between sets, lists, etc. allocates an iterator and therefore allocates memory. Therefore, this should be avoided.

Is Java's own syntax for iterating over memory allocating arrays?

Object[] array = getArray() for(Object elem: array){ //do something } 

(I suppose I could always use the old-fashioned for loop with an index variable.)

+4
source share
2 answers

Nope. In all compilers I checked, this is done by the for loop (0..array.lengh-1).

Note that Java arrays do not implement Iterable . This can be seen, for example, with the following code:

 Object[] arr = new String[100]; Iterable<?> iter = arr; // Error: 'Type mismatch: // cannot convert from Object[] to Iterable<?>' 

[UPDATE]

And here is a specific source: http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.14.2

A for a loop such as

 for ( VariableModifiersopt Type Identifier: Expression) Statement 

has the following meaning when the expression is an array of type T []:

 T[] a = Expression; for (int i = 0; i < a.length; i++) { VariableModifiersopt Type Identifier = a[i]; Statement } 
+4
source

He does not allocate new memory. The following foreach loop:

 for (type var : array) { body-of-loop } 

This is equivalent to this:

 for (int i = 0; i < array.length; i++) { type var = array[i]; body-of-loop } 

As you can see, no additional memory is allocated.

+2
source

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


All Articles