简体   繁体   English

用于跨数组迭代的 Java 语法是否分配内存?

[英]Does Java syntax for iteration across arrays allocate memory?

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?用于跨数组迭代的本机 java 语法是否分配内存?

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

(I suppose I could always use the old-fashioned for loop with an index variable.) (我想我总是可以使用带有索引变量的老式 for 循环。)

Nope.不。 In all compilers that I have checked this is implemented by a for loop (0..array.lengh-1).在我检查过的所有编译器中,这是由for循环 (0..array.lengh-1) 实现的。

Note that Java arrays do not implement Iterable .请注意,Java 数组不实现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这是明确的来源: https : //docs.oracle.com/javase/specs/jls/se13/html/jls-14.html#jls-14.14.2

A for loop such as一个 for 循环,例如

for ( VariableModifiersopt Type Identifier: Expression) Statement

has the following meaning when Expression is an array of type T[]:当 Expression 是 T[] 类型的数组时,具有以下含义:

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

It doesn't allocate new memory.它不分配新内存。 The following foreach loop:以下 foreach 循环:

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

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 allocation is being made.如您所见,没有进行额外的内存分配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM