这个 forEach() 方法 ArrayDeque 是从接口继承的 JAVAlang.Iterable .如果该方法指定了迭代顺序,则该操作将按该顺序执行。方法遍历ArrayQue的Iterable的每个元素,直到该方法处理完所有元素或发生异常为止。操作引发的异常会传递给调用方。
null
语法:
public void forEach(Consumer<? super E> action)
参数: 此方法采用参数名 行动 表示每个元素要执行的操作。
返回: 此方法不返回任何内容。
例外情况: 这种方法很简单 空指针异常 如果指定的操作为空。
下面的程序演示了ArrayQue的forEach()方法:
例1: 演示ArrayQue上的forEach()方法,该方法包含一个字符串值队列。
// Java Program Demonstrate forEach() // method of ArrayDeque import java.util.*; public class GFG { public static void main(String[] args) { // create an ArrayDeque // which contains string values ArrayDeque<String> cities = new ArrayDeque<String>(); // Add Strings to list cities.add( "Kolkata" ); cities.add( "Delhi" ); cities.add( "Bombay" ); cities.add( "Pune" ); // forEach method of ArrayDeque and // print city names cities.forEach((n) -> System.out.println(n)); } } |
输出:
Kolkata Delhi Bombay Pune
例2: 在包含对象队列的ArrayQueue上演示forEach()方法。
// Java Program Demonstrate forEach() // method of ArrayDeque import java.util.*; public class GFG { public static void main(String[] args) { // create an ArrayDeque which going to // contains a list of Objects ArrayDeque<batch> list = new ArrayDeque<batch>(); // Add Objects to list list.add( new batch( "CSE" , 67 )); list.add( new batch( "ECE" , 57 )); list.add( new batch( "IT" , 90 )); list.add( new batch( "ME" , 78 )); // print result System.out.println( "list of Objects:" ); // forEach method of ArrayDeque and // print student names list.forEach((n) -> print(n)); } // printing details of object public static void print(batch n) { System.out.println( "*******************************" ); System.out.println( "Batch Name is " + n.name); System.out.println( "No of Students are " + n.noOfStudents); } } // create a class class batch { String name; int noOfStudents; batch(String name, int noOfStudents) { this .name = name; this .noOfStudents = noOfStudents; } } |
输出:
list of Objects: ******************************* Batch Name is CSE No of Students are 67 ******************************* Batch Name is ECE No of Students are 57 ******************************* Batch Name is IT No of Students are 90 ******************************* Batch Name is ME No of Students are 78
例3: 在ArrayQue上演示forEach()方法的NullPointerException。
// Java Program Demonstrate forEach() // method of ArrayDeque import java.util.*; public class GFG { public static void main(String[] args) { // create an ArrayDeque // which contains string values ArrayDeque<String> cities = new ArrayDeque<String>(); // Add Strings to list cities.add( "Kolkata" ); cities.add( "Delhi" ); cities.add( "Bombay" ); cities.add( "Pune" ); try { // forEach method of ArrayDeque and // print city names cities.forEach( null ); } catch (Exception e) { System.out.println( "Exception: " + e); } } } |
输出:
Exception: java.lang.NullPointerException
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END