2

I have a criteria that is returning a list of strings List<String>.

I have following in the method

 return criteria.list();

But the code shows

 Type safety: Unchecked cast from List to List<String>

To avoid adding @SuppressWarnings("unchecked") and to make sure the types are safely converted (not sure if I should really do it), I read this question and tried to add the solution to my code

 return Collections.checkedList(criteria.list(),List<String>);

but it shows another error as following:

Multiple markers at this line
    - Type safety: Unchecked cast from List to List<String>
    - Syntax error on token ">", Expression expected after this 
     token
  • I do not know if I should really use Collections.checkedList
  • If I should use it, then how to use it?

Thanks

Community
  • 1
  • 1
Jack
  • 6,430
  • 27
  • 80
  • 151

2 Answers2

2

•I do not know if I should really use Collections.checkedList

It is really not necessary in standard implementations, its purpose if mostly for debugging, or if you are receiving a list that you are unsure of and need to make sure it is typesafe(usually because of third party code) or generics have been used and you need to make sure the code is correct at this point as it will throw the exception here and identify what isn't of the correct type.

•If I should use it, then how to use it?

If you were to implement Collections.checkedList the two arguments are the list that is not typesafe and the class that you want a list of, in this case String.class not List<String>

return Collections.checkedList(criteria.list(), String.class);
Sean F
  • 2,352
  • 3
  • 28
  • 40
1

If the method criteria.list() returns a List<String>, then the correct statement would be

return Collections.checkedList(criteria.list(), String.class);

A similar case applies for any other object, e.g. if the method returns a custom object of type Criterion, the answer would be

return Collections.checkedList(criteria.list(), Criterion.class);
PNS
  • 19,295
  • 32
  • 96
  • 143