找出这段程序为何带警告通过编译,却在读取名称时抛出`ClassCastException`。 import java . util . ArrayList ;
import java . util . List ;
public class Main {
public static void main ( String [] args) {
List < String > names = new ArrayList <>();
List raw = names;
raw . add ( 42 );
System . out . println ( names . getFirst () . length ());
}
}
查看答案
上一道练习 审查生成的读数合并器 审查AI代码
问问你的AI 让你的AI把这段代码改成引导式找错练习。
Claude ChatGPT 复制提示词 I am reading "找出这段程序为何带警告通过编译,却在读取名称时抛出`ClassCastException`。" on CodeWiki (https://codewiki.com/zh/practice/spotbug/java/generics/spotbug-raw-list-pollution/).
Context (verbatim from the page):
"""
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
List raw = names;
raw.add(42);
System.out.println(names.getFirst().length());
}
}
"""
Introduce three subtle bugs into the example above and let me find them. Reveal each answer only after I have guessed.
Answer in 中文. Keep code examples in java. Where you are unsure, say so.