Java does not have repeated generics; a list does not carry the type of its elements at runtime. Thus, attempting to throw a restricted type will give you a warning; you might think you know the type, but the compiler reminds you what might be wrong.
You can attribute it to an unrelated collection, and then check the type of each individual item.
List<?> tmp = (List<?>) session.getAttribute("qList"); if (tmp != null) { for (Object o : tmp) { Question q = (Question) o; } }
If you need to pass the List<Question> to any API, you can copy the elements to a new, correctly declared list inside the loop. Obviously, this is a lot of a mess that you must consider in the utility method. But to make it flexible, you probably want to use dynamic types.
public static <T> List<T> asList(Collection<?> c, Class<? extends T> type) { if (c == null) return null; List<T> list = new ArrayList(c.size()); for (Object o : c) list.add(type.cast(o)); return list; } List<Question> qList = asList((Collection<?>) session.getAttribute("qList"), Question.class);
There are methods in java.util.Collections that do almost what you need; Unfortunately, they do not check the type of items in the original packaged collection. In addition, since they wrap the base collection, rather than creating a new independent collection, they can still generate type errors.
Fortunately, the second question is simple:
List<ExamSchedule> eList = new ArrayList<>();
source share