Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java syntax for iteration across arrays allocate memory?

Tags:

java

I am programming for a memory-constrained device. Hence, I want to avoid allocating any memory.

Obviously, iterating across sets, lists, etc will allocate an iterator and thus allocate memory. So this should be avoided.

Does the native java syntax for iterating across arrays allocate memory?

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

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

like image 750
jhourback Avatar asked Feb 22 '23 20:02

jhourback


1 Answers

Nope. In all compilers that I have checked this is implemented by a for loop (0..array.lengh-1).

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

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

[UPDATE]

And here is the definite source: https://docs.oracle.com/javase/specs/jls/se13/html/jls-14.html#jls-14.14.2

A for loop such as

for ( VariableModifiersopt Type Identifier: Expression) Statement

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

T[] a = Expression;
for (int i = 0; i < a.length; i++) {
       VariableModifiersopt Type Identifier = a[i];
       Statement
}
like image 103
Itay Maman Avatar answered Mar 15 '23 21:03

Itay Maman