forEach( )方法
ArrayList集合: 中重写了该方法. 内部使用的是普通for循环, 依然是不可以调用集合的方法对集合进行修改的, 只能通过元素自带的set()方法进行修改, 如果是 基本数据类型 那么就一点都不可以进行修改.
复制代码
1
2
3
4
5
6
7
8
9
10
11
12@Override public void forEach(Consumer<? super E> action) { Objects.requireNonNull(action); final int expectedModCount = modCount; final Object[] es = elementData; final int size = this.size; for (int i = 0; modCount == expectedModCount && i < size; i++) action.accept(elementAt(es, i)); // 需要重写accept() 方法 if (modCount != expectedModCount) // 一旦修改了元素就会在这里检查不通过,报错 throw new ConcurrentModificationException(); }
复制代码
1
2
3
4
5
6
7
8
9
10
11@FunctionalInterface public interface Consumer<T> { void accept(T t); default Consumer<T> andThen(Consumer<? super T> after) { Objects.requireNonNull(after); return (T t) -> { accept(t); after.accept(t); }; } }
方法的使用:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13public class ArrayListTest { public static void main(String[] args) { ArrayList<String> list=new ArrayList<>(); list.add("张三"); list.add("李四"); list.add("王五"); list.add("赵六"); //遍历 list.forEach(s -> System.out.println(s)); } }
LinkedList集合, TreeSet 集合,HashSet集合,中都有forEach() 方法. 方法都比较类似~
HashMap集合:中重写了该方法. 内部使用的是增强for进行遍历,
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16@Override public void forEach(BiConsumer<? super K, ? super V> action) { Node<K,V>[] tab; if (action == null) throw new NullPointerException(); if (size > 0 && (tab = table) != null) { int mc = modCount; for (Node<K,V> e : tab) { for (; e != null; e = e.next) action.accept(e.key, e.value); // 这里的accept 方法, 在下面. 是一个抽象方法,需要重写, } if (modCount != mc) throw new ConcurrentModificationException(); } }
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17@FunctionalInterface public interface BiConsumer<T, U> { void accept(T t, U u); default BiConsumer<T, U> andThen(BiConsumer<? super T, ? super U> after) { Objects.requireNonNull(after); return (l, r) -> { accept(l, r); after.accept(l, r); }; } }
TreeMap集合:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13@Override public void forEach(BiConsumer<? super K, ? super V> action) { Objects.requireNonNull(action); int expectedModCount = modCount; for (Entry<K, V> e = getFirstEntry(); e != null; e = successor(e)) { action.accept(e.key, e.value);// 需要重写了该方法 if (expectedModCount != modCount) { throw new ConcurrentModificationException(); } } }
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15@FunctionalInterface public interface BiConsumer<T, U> { void accept(T t, U u);// 抽象方法 default BiConsumer<T, U> andThen(BiConsumer<? super T, ? super U> after) { Objects.requireNonNull(after); return (l, r) -> { accept(l, r); after.accept(l, r); }; } }
数组:
数组里面没有对应的方法. 直接调会出错.
复制代码
1
2
3
4
5
6
7
8
9
10
11public class Test { public static void main(String[] args) { int[] arr={1,2,5,7,8}; // arr.forEach() // 无法调出来该方法,直接打出来会报红. String[] srr={"fjdsjf","fhudaf"}; // srr.forEach(); } }
欢迎大家评论点赞,讨论~
最后
以上就是义气自行车最近收集整理的关于java中的forEach()方法的全部内容,更多相关java中内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复