I need a Map container that contains either an
Item Object
or
List<Item> Object
as its value, and I can get it out without casting, is it possible?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Short answer: No.
Union types don’t exist in Java. The closest thing you could do in order to get compile-time type checking would be to create list of some custom wrapper class which contained either an
Aor aList<A>, something like the following:At least you wouldn’t be able to create instances of this class that weren’t either an
Aor aList<A>, but getting the value back out would still have to just beObject, with associated casting. This could get quite clumsy, and on the whole it’s probably not worth it.In practice I’d probably just have a
List<Object>with some comments around being very careful about what data types are accepted. The problem is that even run-time checks (sub-optimal) aren’t going to be possible, since Java’s generic erasure means that you can’t do aninstanceof Acheck at runtime (doubly so on the generic parameter of theList).