3
List<SomeClass<String>> list = new ArrayList<SomeClass<String>>();
List l = Collections.checkedList(list, SomeClass.class);

That is my code.Eclipse tell me there are some errors:

The method checkedList(List<E>, Class<E>) in the type Collections is not applicable for the arguments (List<SomeClass<String>>, Class<SomeClass>)

how to use checkedList? how to alter the code?

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Zhao Evlix
  • 41
  • 5

3 Answers3

2

Java cannot check the generic parameter of a type at runtime (How to get a class instance of generics type T), so checkedList will not be able to enforce the <String> part of your type signature.

You can add casting to allow this method call, so checkedList will enforce that only instances of SomeClass<?> are added to the List, but you won't have complete type safety at runtime.

Community
  • 1
  • 1
Joe
  • 29,416
  • 12
  • 68
  • 88
1

You could cast the Class<SomeClass> to raw Class to make it compile.

List<SomeClass<String>> list = new ArrayList<>();
List l = Collections.checkedList(list, (Class)SomeClass.class);

Note that you can't check type parameters at runtime due to type erasure.

fabian
  • 80,457
  • 12
  • 86
  • 114
0

Problem is that you can't have class literals of generic type in Java: Java: how do I get a class literal from a generic type? and for List containing <Foo<Bar>> your class literal would have to be Foo<Bar>.class.

Anyway since checkedList will add type safety checks at runtime you can try using one of dirty solutions like raw types:

List<SomeClass<String>> list = new ArrayList<>();
List l = Collections.checkedList((List)list, SomeClass.class);
Community
  • 1
  • 1
Pshemo
  • 122,468
  • 25
  • 185
  • 269