您的位置:首页 > 其它

forEach如何遍历集合元素

2018-03-13 15:38 746 查看
知识点:

①集合遍历

②Lambda

③泛型

最近学习集合的时候看到下面的代码,

/*这个程序调用了Iterable的forEach()默认方法来遍历几何元素,
传给方法的是参数是Lambda表达式,
该表达式的目标类型是Comsumer。
forEach方法会自动的将几何元素逐个的传给Lambda表达式,
因此Lambda就可以遍历到几何元素了。
*/
import java.util.ArrayList;
import java.util.List;
public class myList {
public static void main(String[] args) {
List strList=new ArrayList();
strList.add("Hello");
strList.add("World!!!");
strList.forEach(str->
System.out.println( ((String)str).length()
));
}
}


对forEachforEach方法会自动的将几何元素逐个的传给Lambda表达式,不是太明白就仔细看了看,复习了了Lambda式和forEach集合遍历。

1、ArrayList类与接口的关系:

ArrayList 实现了List接口,List的接口又继承了,Collection、Iterable,如下图:



2、JAVA8之后,Iterable接口新增了一个forEach(Comsumer action)默认方法



因为List接口继承了Iterable接口,所以List集合也可以直接调用该方法。

再看forEach()函数的参数,为Consumer接口,该接口就只有一个抽象方法
void accept(T t);
,所以为函数式接口,可以用Lambda表达式实现。

实现了List的接口的类ArrayList,它重写了forEach方法源代码如下

@Override
/*Consumer<? super E> action 泛型的类型通配符
<? extends E>表示泛型   是E或者E的子类(extends意义上:相当于≤)
<?  super  E>表示泛型   是E或者E的父类(super意义上:相当于≥)
*/

public void forEach(Consumer<? super E> action) {
//检查action不为空
Objects.requireNonNull(action);
final int expectedModCount = modCount;
@SuppressWarnings("unchecked")
/*elementData的定义: transient Object[] elementData;
下面语句将elementData由Object[]转换为E[]
*/
final E[] elementData = (E[]) this.elementData;
final int size = this.size;
/*★★★★将会循环的调用Lambda表达式★★★★
(str-> System.out.println( ((String)str).length())
把elementData[i]作为参数传给str,然后执行Lambda表达式
实现的语句
*/
for (int i=0; modCount == expectedModCount &&
i < size; i++) {
action.accept(elementData[i]);
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息