close

一. 題目

Given the code fragment:

A. 1John2null

B. 12

C. A NullPointerException is thrown at run time.

D. A compilation error occurs.

 

二. 答案

D

 

三. 解析

image

iStr是泛型為List<String>的 Stream流。

 

若使用 flatMapToInt(),return IntStream,無法使用 Stream<T>去操縱

image

 

改變承接變數的型態改成 IntStream

image

 

這個時候 x.stream(),把 iStr的每個元素變成 Stream<String>,與回傳型態 IntStream不相符,會出現型態轉換錯誤。

只要在 x.stream後面加上.mapToInt(Integer::valueOf),即可編譯成功。

image

 

但執行程式時,因為 iStr含有非數字的值 "John",

所以發生錯誤 Exception in thread "main" java.lang.NumberFormatException: For input string: "John"

image

arrow
arrow

    書童 發表在 痞客邦 留言(0) 人氣()