博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java中普通for循环和增强for循环的一些区别
阅读量:7080 次
发布时间:2019-06-28

本文共 2145 字,大约阅读时间需要 7 分钟。

Java中for的几种常见形式

1.For loop using index.

for (int i = 0; i < arr.length; i++) {     type var = arr[i];    body-of-loop}复制代码

2.Loop using explicit iterator.

for (Iterator
iter = coll.iterator(); iter.hasNext(); ) { type var = iter.next(); body-of-loop}复制代码

3.Foreach loop over all elements in arr.

for (type var : coll) {    body-of-loop}复制代码

For循环用来处理哪些数据结构

1.数组

int[] a = {1,2,3,4,5,6};int[] b = new int[]{1,2,3,4,5,6};int[] c = new int[6];for (int i = 0; i < a.length; i++) {    System.out.println(i);}for (int i : a) {    System.out.println(i);}复制代码

2.实现了java.util.Iterator的类

import java.util.Iterator;public class IterableTest
implements Iterable
{ public static void main(String[] args) { IterableTest
integers = new IterableTest
(); for (Integer integer : integers) { System.out.println(integer); } } @Override public Iterator
iterator() { return new Iterator() { @Override public boolean hasNext() { //... return false; } @Override public Object next() { //... return null; } @Override public void remove() { //... } }; }}复制代码

普通for遍历和增强for的一些区别

增强的for循环的底层使用迭代器来实现,所以它就与普通for循环有一些差异

  1. 增强for使用增强for循环的时候不能使用集合删除集合中的元素;
  2. 增强for循环不能使用迭代器中的方法,例如remove()方法删除元素;
  3. 与普通for循环的区别:增强For循环有遍历对象,普通for循环没有遍历对象;

对于实现了RandomAccess接口的集合类,推荐使用普通for,这种方式faster than Iterator.next

The RandomAccess interface identifies that a particular java.util.List implementation has fast random access. (A more accurate name for the interface would have been "FastRandomAccess.") This interface tries to define an imprecise concept: what exactly is fast? The documentation provides a simple guide: if repeated access using the List.get( ) method is faster than repeated access using the Iterator.next( ) method, then the List has fast random access. The two types of access are shown in the following code examples.

参考资料

转载地址:http://hdvml.baihongyu.com/

你可能感兴趣的文章
翻译连载 |《你不知道的JS》姊妹篇 |《JavaScript 轻量级函数式编程》- 第 8 章:列表操作...
查看>>
Linux常用的系统监控shell脚本
查看>>
Android Studio中使用GreenDao
查看>>
Yii 框架之采用自带的jquery库实现ajax分页
查看>>
负载均衡小demo,未实现session共享
查看>>
Android广播-个人总结
查看>>
redis java客户端Jedis 实现 连接池 + 简单的负载均衡
查看>>
python的string.strip(s[, chars])方法的各种小细节
查看>>
new Date() 在Safari下的 Invalid Date问题
查看>>
Mac OSX升级10.14后,sequel pro关闭时闪退crash解决办法
查看>>
Mybatis 框架源码分析
查看>>
关于 LF will be replaced by CRLF 问题出现的原因以及解决方式
查看>>
HTML5编程之旅 第3站 WebSockets
查看>>
oracle 体系结构及内存管理 05_重建EM
查看>>
everedit
查看>>
改写源代码,使得认证成功后跳转到successUrl路径
查看>>
浅析CentOS和RedHat Linux的区别
查看>>
Linux gcc版本如何升级
查看>>
Lubuntu Next 18.10将默认采用Calamares
查看>>
思达报表工具Style Report基础教程—简单列表
查看>>