Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warning: [unchecked] unchecked conversion

Tags:

java

I am facing an issue with generics here. Can anyone please point me what I am missing over in the below statements?

1.

warning: [unchecked] unchecked conversion

List<Question> qList = (List) session.getAttribute("qList");
                                       ^
  required: List<Question>
  found:    List

2.

warning: [unchecked] unchecked conversion

List<ExamSchedule> eList = new <ExamSchedule>ArrayList();

required: List<ExamSchedule>
found:    ArrayList

I don't want to supress the warnings. Any suggestions will be appreciated.

like image 920
Sharad Tank Avatar asked May 10 '13 04:05

Sharad Tank


2 Answers

List<Question> qList = (List) session.getAttribute("qList");
  1. session.getAttribute("qList"); will return instance of type Object. So you need to explicitly cast it.

  2. (List) is just raw type, List<String> is generic type , so trying to cast raw type to generic type reference gives a warning.

Now, if you do this:

List<Question> qList = (List<Question>) session.getAttribute("qList");

The cast is a runtime check but there will be a type erasure at runtime, so there's actually no difference between a List<String> and List<Foo> etc.Hence you get that error. So try (List<?> list) This type conversion verifies that the object is a List without caring about the types held within.

List<ExamSchedule> eList = new <ExamSchedule>ArrayList();

That is a syntax error.It should be ArrayList<ExamSchedule> , not <ExamSchedule>ArrayList.

Suggestions :

List<?> qList = (List<?>) session.getAttribute("qList");
List<ExamSchedule> eList = new ArrayList<ExamSchedule>();
like image 121
AllTooSir Avatar answered Oct 02 '22 23:10

AllTooSir


Answer 1:

List<Question> qList = (List<Question>) session.getAttribute("qList");

Answer 2:

List<ExamSchedule> eList = new ArrayList<ExamSchedule>();

Grasp first the idea of Generics.

As for the first answer, if you're using HttpSession, there is no chance of calming the warnings without annotating your statement with @SuppressWarnings like so:

@SuppressWarnings("unchecked")
List<Question> qList = (List<Question>) session.getAttribute("qList");

This is due to the Servlet API which returns an Object from HttpSession.getAttribute(). The compiler will warn you of type-safety (unchecked cast from Object to List<Question>) otherwise.

like image 31
Buhake Sindi Avatar answered Oct 02 '22 22:10

Buhake Sindi