ジェネリックスを使用してコレクション用の小さなコードを書いていましたが、そのコードは以下のとおりです。Javaジェネリックスを学ぶ
import java.util.*;
// one class needs to have a main() method
public class HelloWorld
{
// arguments are passed using the text field below this editor
public static void main(String[] args)
{
List<?> list1 = new ArrayList<?>();
list1.add("Zahid");
list1.add(22);
System.out.print(list1.toString());
}
}
誰かがこのコードの何が問題なのか説明できます。 以下のエラーが発生しています。
error: unexpected type
List<?> list1 = new ArrayList<?>();
^
required: class or interface without bounds
found: ?
HelloWorld.java:11: error: no suitable method found for add(String)
list1.add("Zahid");
^
method Collection.add(CAP#1) is not applicable
(argument mismatch; String cannot be converted to CAP#1)
method List.add(CAP#1) is not applicable
(argument mismatch; String cannot be converted to CAP#1)
where CAP#1 is a fresh type-variable:
CAP#1 extends Object from capture of ?
HelloWorld.java:12: error: no suitable method found for add(int)
list1.add(22);
^
method Collection.add(CAP#1) is not applicable
(argument mismatch; int cannot be converted to CAP#1)
method List.add(CAP#1) is not applicable
(argument mismatch; int cannot be converted to CAP#1)
where CAP#1 is a fresh type-variable:
CAP#1 extends Object from capture of ?
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
3 errors
あなたはジェネリック型を指定する必要があります( '一覧')または「許可」のすべてのタイプの '一覧<と: は、ワイルドカードの詳細を知るには?オブジェクト>を拡張します。しかし、第2版は利点がないので、最初の版を好むべきです。 –
@PJvGリスト> list1 = new ArrayList >();をコンパイルすることはできますが、Slimuは無限のワイルドカードタイプのリストに 'null 'を追加することしかできないと答えました。 –
@StefanWarminski右、私は間違った言い方で、私は彼ができないことを意味しました。リスト> list1 = new ArrayList >(); 'list1.add(" Zahid ");'が続きます。 Slimuの答えが問題を説明するのに十分であるため、コメントを削除します。 – PJvG