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.)
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With