I have two methods, the first needs a Map<ItemA, ItemB> the second a Map<ItemA ,ItemB[]>. How can I create a generic Map that covers both cases?
I have two methods, the first needs a Map<ItemA, ItemB> the second a Map<ItemA
Share
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.
You cannot. How is this going to work? If the first method does a
map.get(key)and gets anItemB[]instead of anItemB, it’ll complain with aClassCastException.The whole point of generic collections is to separate these two cases.
You could make a wrapper that wraps a
Map<ItemA, ItemB>as aMap<ItemA, ItemB[]>, returning an array with just one element for everything. But this may cause trouble with array manipulation semantics.Maybe just copy everything:
The other direction (converting
ItemB[]into a singleItemB) does not work in general.