在for循环里面如果有if语句判断,当业务中有一条符合要求并且取到合适的值的时候,这时候可以在if判断完后加一个break,这样for循环语句不会一直循环下去,节约了程序的性能
java中迭代器效率高
ArrayList实现了RandomAccess接口,RandomAccess接口为ArrayList带来了什么好处呢?
我们查看一下RandomAccess的源码文档,发现有这样一段描述:
As a rule of thumb, a List implementation should implement this interface if, for typical instances of the class, this loop:
for (int i=0, n=list.size()i <ni++)
list.get(i)
runs faster than this loop:
for (Iterator i=list.iterator()i.hasNext())
i.next()
从描述中,可以看出实现RandomAccess接口的集合类,使用for循环的效率会比Iterator高。
RandomAccess接口为ArrayList带来的好处:
1、可以快速随机访问集合。
2、使用快速随机访问(for循环)效率可以高于Iterator。