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.
List<Question> qList = (List) session.getAttribute("qList");
session.getAttribute("qList");
will return instance of type Object
. So you need to explicitly cast it.
(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>();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With