Code Fix

上級 › raw type とワイルドカードの使い分け › パターン4

raw type とワイルドカードの使い分け

型引数を省くと型安全が失われます。

 1  import java.util.ArrayList;
 2  import java.util.List;
 3  public class Main {
 4      public static void main(String[] args) {
 5          List list = new ArrayList();
 6          list.add("a");
 7          list.add(____);
                       ^
 8          for (Object o : list) {
 9              String s = (String) o;
10              System.out.println(s);
11          }
12      }
13  }
Exception in thread "main" java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.Stringexited with code 1

空欄を埋めてビルドを通す

広告
広告スロット(未設定)

raw type とワイルドカードの使い分け

List<Object>とList<?>の違いも整理します。

このエラーの解説と類題をまとめて見る →

広告
広告スロット(未設定)