I want a Set which only holds one data type and doesn’t permit any of its superclasses or subclasses from being added to the Set.
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 can use
Object.getClass()do determine the type of your objects.if you want a guarantuee that only classes of a type MyClass are added you could just extend HashSet and override the
add(Object o)method and only add the element to the collectionif (o.getClass() == MyClass.class):Update: added a working example that you can run as PoC.
running this example yields: