I have to define a List and it has two types of possible values
- String
- Some user defined Class
How can I make a List that is type safe in that it only accepts these two types?
I want to avoid the use of raw List.
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.
This does what you are asking for (with a runtime error):
There is no way to implement this in Java that will give you a compile time error you add an element of the wrong type (in your sense) to a
List. However, if this was not aList, you could define the class to have overloadedaddmethods, etcetera. Creating new “adder” methods won’t help you here because the existingadd(T)method will still exist in the interface. No matter what you do (in Java), it won’t be a compile time error to call it.