Java的循环差异 [英] Java For Loop differences

查看:158
本文介绍了Java的循环差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些语句在Java的内存占用和效率方面是完全相同的?



首先:

Are these statements completely the same in terms of memory occupation and efficiency in Java?

First:

Object[] array = new Object[100];
int i = 0;
for (; i < array.length; i++){
   Object o = array[i];
   //do something
}

第二

Object[] array = new Object[100];
for (int i = 0; i < array.length; i++){
   Object o = array[i];
   //do something
}

第三

Object[] array = new Object[100];
for (Object o : array){
   //do something
}


推荐答案

在内存占用和效率方面,是的。但是,有区别。首先, i 存在(有一个作用域)在循环之外;而在第二它不。在第三种情况下,没有(直接)访问索引或改变当前对象位置的数组内容。

In terms of memory occupation and efficiency, yes. However, there are differences. In the first, i exists (has a scope) beyond the loop; while in the second it does not. In the third case, there is no (direct) way to access the index or to change the array contents at the position of the current object.

这篇关于Java的循环差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆